Rimossi i provider integrati OpenAI, Bedrock e GCP e ogni fallback a OpenAI (B)
Parte "sicurezza" della fase 3 di aKode (e39aae00), senza le funzioni di imeAI:
- via i provider integrati openai, amazon-bedrock, amazon-bedrock-runtime e gcp
(crate model-provider: moduli amazon_bedrock, gcp, chatgpt_base_url; login Bedrock;
onboarding Bedrock/GCP; richieste app-server di setup cloud);
- nessun URL predefinito verso api.openai.com / chatgpt.com: un provider senza
base_url non viene mai contattato; senza model_provider configurato exec e TUI
mostrano come scriverne uno in config.toml (NO_MODEL_PROVIDER_CONFIGURED_ERROR);
- via la skill openai-docs, la sample skill-installer (scaricava da github.com/openai/skills),
request_plugin_install, AppsInstructions, URL predefiniti di realtime e updater;
- test di sicurezza adattati (provider "mock" al posto di quello integrato), non cancellati.
Restano fuori da questo commit (categoria F/D/E, non portate): chiave per provider nel
portachiavi, modelli da /models, unione dei messaggi di sistema, crate web-tools e
SearXNG, header @@ in apply_patch, modello ausiliario, tool function per apply_patch.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf of
|
||||
any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don\'t include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,20 +0,0 @@
|
||||
---
|
||||
name: openai-docs
|
||||
description: API first-timers, Codex/Work Q&A. If the user already has an OpenAI API integration, skip this skill for API questions and use the developer docs. Read this skill before answering how Codex or ChatGPT Work behaves, where to find a feature, or how to configure or troubleshoot this app or coding agent. This includes conversation history, model and cache behavior, instruction precedence, permissions, and tool availability. Use for API onboarding only when the user is connecting to the OpenAI API for the first time. Skip action requests, such as scheduling an automation, and tasks fully answered by supplied text or data.
|
||||
---
|
||||
|
||||
# Codex and ChatGPT Work
|
||||
|
||||
Use this skill for Codex and ChatGPT Work capabilities and behavior, first OpenAI API integrations, and OpenAI API model migrations when the user explicitly invokes `$openai-docs`. For other requests, continue with the user's task and consult the relevant official documentation when needed.
|
||||
|
||||
Identify the product and surface the user means. If they ask what you can do in this chat, check the tools and settings available here before making a claim about their access.
|
||||
|
||||
For broad questions about Codex setup or team customization, first read [Codex self-knowledge](references/codex-self-knowledge.md) for guidance on choosing and combining configuration options.
|
||||
|
||||
For other questions about product behavior, look up the current Codex guide at developers.openai.com/codex or the ChatGPT Work guide at learn.chatgpt.com. Open the page for the surface the user is asking about.
|
||||
|
||||
For a recent change, or when a source explains only the underlying mechanism, find the feature by name in the [ChatGPT and Codex changelog](https://learn.chatgpt.com/docs/changelog). Use the entry for the relevant surface and version. For Codex client behavior, follow the linked change or tests to verify what the client actually does. Cite what establishes the answer and say which details remain uncertain.
|
||||
|
||||
For a first OpenAI API integration, start with the [developer quickstart](https://developers.openai.com/api/docs/quickstart) and follow the guide for the user’s task. Suggest the OpenAI Developers plugin for deeper implementation help.
|
||||
|
||||
When the user explicitly invokes `$openai-docs` for an OpenAI API model migration, use the official migration guide for the requested target. For GPT-6 models, start with the [migration quickstart](https://developers.openai.com/api/docs/guides/latest-model#migration-quickstart). Inspect the existing request and prompt, verify compatibility for changed parameters, and preserve supported behavior and the user's chosen target model.
|
||||
@@ -1,6 +0,0 @@
|
||||
interface:
|
||||
display_name: "OpenAI Docs"
|
||||
short_description: "Codex and ChatGPT Work Q&A, plus first-time API setup"
|
||||
icon_small: "./assets/openai-small.svg"
|
||||
icon_large: "./assets/openai.png"
|
||||
default_prompt: "Use $openai-docs to explain a Codex or ChatGPT Work feature, help with my first OpenAI API integration, or migrate a request to my chosen model."
|
||||
@@ -1,3 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="currentColor" viewBox="0 0 14 14">
|
||||
<path d="M10.931 3.34a.112.112 0 0 0-.069-.104l-.038-.007c-1.537.05-2.45.318-3.714 1.002v6.683c.48-.248.936-.44 1.414-.58.695-.203 1.417-.292 2.303-.305l.038-.008a.113.113 0 0 0 .066-.104V3.341ZM2.363 9.919c0 .064.051.11.105.111l.33.008c1.162.046 2.042.243 2.975.662-.403-.585-1.008-1.075-1.654-1.292a.991.991 0 0 1-.674-.941v-5.14a6.36 6.36 0 0 0-.59-.076l-.37-.02a.115.115 0 0 0-.122.111v6.577Zm9.455-.001a.998.998 0 0 1-.877.992l-.101.007c-.832.012-1.47.095-2.066.27-.599.174-1.176.448-1.883.863a.444.444 0 0 1-.449 0c-1.299-.763-2.229-1.07-3.689-1.125l-.299-.008a.997.997 0 0 1-.977-.998V3.342c0-.573.478-1.017 1.038-.999l.417.023c.188.015.35.037.513.062v-.754c0-.708.749-1.244 1.429-.903.984.492 1.836 1.449 2.15 2.505 1.216-.617 2.222-.884 3.771-.934l.105.003a.998.998 0 0 1 .918.996v6.576ZM4.332 8.466c0 .049.03.087.07.1l.24.091a4.319 4.319 0 0 1 1.581 1.176V3.721c-.164-.803-.799-1.617-1.584-2.07l-.162-.088c-.025-.012-.054-.013-.088.009a.12.12 0 0 0-.057.102v6.792Z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.1 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1.4 KiB |
@@ -1,71 +0,0 @@
|
||||
# Codex self-knowledge
|
||||
|
||||
Use this manual-first route only for genuinely broad Codex setup, orientation, customization, troubleshooting, local-state guidance, or system-map synthesis across skills, plugins, MCP, hooks, `AGENTS.md`, automations, and product surfaces. Mixed Chat/Work/Codex comparisons belong to `official-docs.md` instead.
|
||||
|
||||
Narrow Codex documentation questions require official documentation search first, then an actual page open or fetch using an available documentation or official-domain web capability. This includes a single feature such as Codex Goals, a specific setting, documented behavior, exact error, or requested page citation. Search and fetch the exact official topic before inspecting local files or bundled references. Do not fetch the manual, read bundled references, inspect local configuration or caches, or turn a targeted documentation lookup into broad product synthesis. Current or latest model questions follow the model-selection route.
|
||||
|
||||
## Start with the manual
|
||||
|
||||
Reuse a manual path and outline path already established in the same thread when both remain usable and current. Refresh before relying on a path fetched more than about a day ago, obtained from another thread or uncertain source, or missing likely-current information.
|
||||
|
||||
Otherwise, run the bundled manual helper first. Skip it without probing only when policy explicitly makes the session read-only, shell execution unavailable, or every allowed temporary cache location unavailable. Workspace-only write access is not enough: the helper needs an allowed writable temp cache. A guessed sandbox restriction is not evidence that the helper is unavailable.
|
||||
|
||||
Resolve `<skill-dir>` to the actual installed skill directory, then run:
|
||||
|
||||
```bash
|
||||
node <skill-dir>/scripts/fetch-codex-manual.mjs
|
||||
```
|
||||
|
||||
The helper automatically chooses the first usable cache location in this order:
|
||||
|
||||
1. `$TMPDIR/openai-docs-cache`
|
||||
2. `%TEMP%\openai-docs-cache`
|
||||
3. `%TMP%\openai-docs-cache`
|
||||
4. `/private/tmp/openai-docs-cache`
|
||||
5. `/tmp/openai-docs-cache`
|
||||
|
||||
Use an explicit override only when the allowed cache must be selected manually:
|
||||
|
||||
```bash
|
||||
node <skill-dir>/scripts/fetch-codex-manual.mjs --cache-dir <cache-dir>
|
||||
```
|
||||
|
||||
On Windows, `%TEMP%` and `%TMP%` are discovered automatically; `$env:TEMP\openai-docs-cache` is a typical PowerShell override. The helper handles configured HTTP(S) proxies and falls back to `curl` when needed. Do not require a POSIX-only environment prefix or an unnecessary cache override.
|
||||
|
||||
The helper verifies the current source and returns a manual path, outline path, freshness status, and heading outline. Use that outline to locate relevant headings and line ranges, then read or search only the returned manual and outline paths. Do not inspect unrelated repositories, caches, source trees, or local state to establish a public Codex product claim.
|
||||
|
||||
For follow-up questions in the same thread, reuse those fresh paths instead of fetching again. If asked whether the manual is current enough to rely on now, rerun the helper when an allowed temp cache is available and answer from its reported status and returned paths.
|
||||
|
||||
## Fill only genuine documentation gaps
|
||||
|
||||
If the manual answers a claim, stop retrieving sources for that claim. Its official source pages and known anchors are sufficient citation support. Continue the user's broader task when the documentation lookup was only one dependency.
|
||||
|
||||
If the helper was legitimately skipped, actually fails, or the fresh manual lacks a material or likely-current claim, use the narrowest official follow-up. Search the exact topic using an available documentation or approved-domain web capability, then actually open or fetch a clearly relevant official result. A page-specific citation can justify the same narrow follow-up.
|
||||
|
||||
For an undocumented Codex term, mode, acronym, or exact error, first check adjacent manual terminology. Map it to the closest documented concept when possible. If the exact term is material or likely current, perform one targeted official search-and-fetch; if it remains undocumented, say so. Do not expand into internal knowledge bases, private source trees, guessed roadmap details, or account-specific workarounds.
|
||||
|
||||
If official documentation conflicts with a callable capability verified in the current session, explicitly state the conflict and prefer that verified behavior for this environment. Otherwise, resolve unsupported claims with bounded uncertainty or route the user to support, an administrator, or product feedback.
|
||||
|
||||
## Choose the smallest matching Codex surface
|
||||
|
||||
- Prompt or thread context: one-off task constraints.
|
||||
- Repository `AGENTS.md`: durable team conventions, commands, and verification expectations; nested files apply more specifically within their subtree.
|
||||
- Project `.codex/config.toml`: settings for a trusted repository, including sandbox, MCP, hooks, model, and reasoning defaults.
|
||||
- Global config or global guidance: personal defaults across repositories.
|
||||
- Skill: a reusable workflow, optionally with focused references or scripts.
|
||||
- Plugin: an installable bundle of skills, tools, commands, MCP configuration, hooks, apps, assets, or related metadata.
|
||||
- MCP server or app connector: authorized live external data and actions. Use an authenticated connector, not web search or memory, for private Google Docs, Calendar, Slack, GitHub, Notion, or similar workspace data.
|
||||
- Automation: scheduled checks, reminders, monitors, or follow-ups; use an existing-thread heartbeat when continuity matters.
|
||||
- Hook: mechanical enforcement around lifecycle events, tool calls, commands, or edits.
|
||||
|
||||
Split requests that combine one-off, durable, repository-scoped, and recurring behavior instead of forcing them onto a single surface. For example, "always do this, but only for this PR" belongs in the current prompt or thread unless the user explicitly wants persistence or enforcement.
|
||||
|
||||
For a surface recommendation, state what to use, why it fits, what to avoid, and the manual or official documentation supporting the answer.
|
||||
|
||||
For product surfaces, distinguish terminal-first CLI work, editor-attached IDE work, desktop planning or review, hosted cloud execution, in-app browser testing, the user's existing Chrome session, and desktop Computer Use. Keep `config.toml` defaults, `requirements.toml` constraints, and managed or administrator policy separate. An API key does not establish ChatGPT, Codex cloud, connector, or account access.
|
||||
|
||||
For plugin or app failures, check the installed bundle, enabled state, connector authorization, MCP setup, restart or new-thread expectations, and workspace policy before inferring a cause. Route billing, entitlements, undocumented rollout labels, and unsupported access paths to the appropriate support or administrative owner.
|
||||
|
||||
Memory can provide user preferences or context, but explicit prompt instructions win and memory is not a source for current external facts. Sandbox or network denials require narrowly scoped escalation with a clear justification; destructive commands, writes outside the workspace, and broad access changes require explicit approval.
|
||||
|
||||
When a page-specific citation helps, useful official anchors include `concepts/customization#agents-guidance`, `concepts/customization#skills`, `plugins/build#plugin-structure`, `concepts/customization#mcp`, `config-advanced#hooks`, `app/automations#thread-automations`, and `config-reference#configtoml`.
|
||||
@@ -1,15 +0,0 @@
|
||||
# Latest model fallback
|
||||
|
||||
This is a compact, non-authoritative fallback, not a source for current availability, prices, aliases, or defaults. First search for and fetch current official model guidance at `https://developers.openai.com/api/docs/guides/latest-model` and the relevant official model page. The fetched official documentation wins if this snapshot has drifted. Disclose any use of this fallback.
|
||||
|
||||
## Source model descriptions
|
||||
|
||||
| Model ID | Official source description |
|
||||
| --- | --- |
|
||||
| `gpt-6-astra` | For the most demanding reasoning, coding, and professional work. |
|
||||
| `gpt-6.1-sol` | Near-Astra performance for complex work at a lower cost. |
|
||||
| `gpt-6-luna` | Strong performance for focused, high-volume tasks. |
|
||||
|
||||
Use `https://developers.openai.com/api/docs/guides/latest-model/gpt-6-astra.md#migration-quickstart` for an actual GPT-6 migration and `https://developers.openai.com/api/docs/guides/latest-model/gpt-6-astra.md#prompting-best-practices` for requested GPT-6 prompting. Open and read the relevant page before recommending a request shape, reasoning setting, endpoint, tool behavior, or migration.
|
||||
|
||||
Verify GPT-6 Pro against current official Responses and model documentation before describing model IDs, reasoning modes, request parameters, or account availability; do not invent a separate `gpt-6-pro` model slug.
|
||||
@@ -1,27 +0,0 @@
|
||||
# Local documentation MCP setup and diagnostics
|
||||
|
||||
Use this route only when the user explicitly asks to configure or troubleshoot the official OpenAI documentation MCP server in a supported **local Codex client**. A missing documentation tool during an ordinary documentation request is not a setup request: answer with the root skill's official-domain web fallback without installation, sandbox escalation, configuration changes, or restart.
|
||||
|
||||
## Verify the supported local setup
|
||||
|
||||
1. Search and fetch current official Codex MCP setup documentation when those tools are callable. Otherwise, search and fetch the relevant official OpenAI documentation directly.
|
||||
2. Confirm the documented endpoint is `https://developers.openai.com/mcp` and verify the supported command or configuration against that current documentation before recommending it.
|
||||
3. When the current documentation supports it, the local Codex CLI setup is:
|
||||
|
||||
```sh
|
||||
codex mcp add openaiDeveloperDocs --url https://developers.openai.com/mcp
|
||||
```
|
||||
|
||||
The equivalent documented configuration is:
|
||||
|
||||
```toml
|
||||
[mcp_servers.openaiDeveloperDocs]
|
||||
url = "https://developers.openai.com/mcp"
|
||||
```
|
||||
|
||||
4. Check the supported local client's MCP listing or configuration, its enabled state, relevant workspace/admin policy, and any documented authentication requirement. Verify success from the actual command result, configuration, or a callable documentation-tool search/fetch; never claim installation or access without evidence.
|
||||
5. Recommend a local-client restart or new local session only when current official documentation or observed client behavior requires it. Clearly identify which local client must refresh.
|
||||
|
||||
A skill dependency declaration, configured server, or local-client setup does not make a tool callable in an already running session. In particular, editing a hosted container's local configuration cannot install a tool into the host or model's current tool inventory. Never claim a local command installed the server into a current hosted session.
|
||||
|
||||
Only perform a local installation or configuration change when the user explicitly authorizes that change. Never request sandbox escalation, edit hosted configuration, install a dependency, or ask the user to restart a hosted session merely to answer an ordinary documentation question.
|
||||
@@ -1,46 +0,0 @@
|
||||
# Model migration and prompting
|
||||
|
||||
Use this route for model upgrades, migration planning, model-specific prompting, or latest/current/default prompting guidance. First search current official OpenAI documentation for the exact requested topic and model, then open or fetch the relevant official page using an available documentation or official-domain web capability. Do not run a resolver, open bundled references, or rely on a guide URL before completing that official search and actual page fetch.
|
||||
|
||||
## Choose the target before loading more context
|
||||
|
||||
- **Explicit model target:** Preserve the user's exact requested target, including an explicitly requested GPT-5.5 or GPT-5.6 migration. Do not run the latest-model resolver and do not substitute a newer model. Search for and fetch current guidance for that exact model. A GPT-5.6 migration must not load GPT-6 guidance or references.
|
||||
- **Unspecified, latest, current, or default target:** For deprecation-driven migrations, use the retiring model's documented replacement from the [API deprecations page](https://developers.openai.com/api/docs/deprecations) instead of running the latest-model resolver. If no replacement is documented, or the migration is not prompted by a deprecation, search for and fetch `https://developers.openai.com/api/docs/guides/latest-model` first. Use the corresponding `latest-model.md` metadata only when dynamic migration resolution is needed, then run the platform-specific resolver below and preserve its returned model and exact guide URLs.
|
||||
- **Latest/current/default prompting:** Follow the dynamic-target route, then use the returned prompting guide. Do not run the resolver for explicitly named-model prompting.
|
||||
- **Pure model selection:** Use `references/model-selection.md` instead. Do not run the resolver.
|
||||
|
||||
For POSIX shells, invoke the resolver through `sh`, without assuming an executable bit:
|
||||
|
||||
```sh
|
||||
sh <skill-dir>/scripts/resolve-latest-model-info
|
||||
```
|
||||
|
||||
On Windows, use the CommonJS entry point with Node.js 18 or newer:
|
||||
|
||||
```text
|
||||
node <skill-dir>\scripts\resolve-latest-model-info.cjs
|
||||
```
|
||||
|
||||
If the Windows Node runtime is unavailable and `load_workspace_dependencies` is callable, use its returned runtime and retry once. Do not execute the extensionless POSIX wrapper directly on Windows.
|
||||
|
||||
Do not suppress or redirect resolver stdout. Success requires JSON with nonempty `model`, `migrationGuideUrl`, and `promptingGuideUrl` fields. If the command fails or any required field is missing, retry the platform-specific command once, then fall back to current official documentation and finally disclosed bundled references.
|
||||
|
||||
## Retrieve only the guidance this request needs
|
||||
|
||||
Treat returned guide URLs as opaque: fetch those exact URLs without deriving, substituting, or appending a model query. Use an available official documentation or first-party-domain capability to open and read the relevant official page. Retry the exact guide URL when its response contains only a title or no substantive body.
|
||||
|
||||
- Fetch `migrationGuideUrl` for a requested migration or upgrade plan.
|
||||
- Fetch `promptingGuideUrl` only when the user asks for prompting guidance or the migration requires a prompt change. Extract only `## Prompting best practices` through the next H2 heading.
|
||||
- For explicitly named-model prompting, fetch that model's official prompting guidance and extract only `## Prompting best practices` through the next H2 heading. Do not load a migration reference or run the resolver.
|
||||
- For an actual GPT-6 migration or implementation plan, fetch `https://developers.openai.com/api/docs/guides/latest-model/gpt-6-astra.md#migration-quickstart`. For specifically requested GPT-6 prompting, fetch `https://developers.openai.com/api/docs/guides/latest-model/gpt-6-astra.md#prompting-best-practices`. Read `references/upgrading-to-gpt-6-astra.md` only when fetched official guidance does not resolve needed compatibility gates, scoped code changes, tier-aware routing, validation, or other migration-specific judgment. Never load it for documentation-only questions about model tiers, the family alias, Pro mode, reasoning effort, or current guidance when the fetched official documentation already answers them.
|
||||
- Verify current official guidance and account availability before recommending or selecting a model. Preserve the selected model and apply its own compatibility rules; do not copy a sibling's reasoning defaults, tool support, or regional availability. A newer family member does not change the model returned by the latest-model resolver. For an explicitly requested model whose public guidance is not yet available, keep the requested target and state the unresolved compatibility facts instead of silently substituting another model.
|
||||
- Read `references/prompting-guide.md` only when prompting guidance or prompt changes are actually needed and current official guidance is unavailable.
|
||||
- Read `references/upgrade-guide.md` only when current official migration guidance is unavailable. Disclose when a bundled fallback was used.
|
||||
|
||||
## Keep implementation changes scoped
|
||||
|
||||
Change active model defaults and directly related prompt surfaces only when the user requested that work. Update registries, model pickers, capability metadata, routing, pricing, or tests only when they are in scope and current official documentation verifies the relevant values.
|
||||
|
||||
Preserve each workload's cost, latency, quality, reasoning, tool, endpoint, and output-contract role. Do not collapse a tiered router into one flagship model, replace intentionally pinned fallbacks, or rewrite historical examples, fixtures, eval baselines, provider comparisons, or unrelated SDK and authentication configuration.
|
||||
|
||||
If a safe migration requires an endpoint change, request-schema change, tool-handler change, or other implementation outside the requested scope, report the exact compatibility blocker and smallest follow-up instead of silently changing behavior.
|
||||
@@ -1,12 +0,0 @@
|
||||
# Model selection
|
||||
|
||||
Use this route for model recommendations, comparisons, and latest/current/default choices when the user is not requesting a migration or prompting guidance.
|
||||
|
||||
1. Search current official OpenAI documentation for the exact requested workload and any explicitly named model; then open or fetch the relevant official page. For current or latest family guidance, use `https://developers.openai.com/api/docs/guides/latest-model`.
|
||||
2. Use any available official documentation or first-party-domain search. Read the actual source; do not make a recommendation from a search snippet, guessed default, or bundled snapshot.
|
||||
3. Match the documented model to the user's requested modality, quality, latency, cost, context, and workload. Distinguish flagship, balanced, high-throughput, coding, audio, image, or other specialized roles only when the fetched current documentation supports the distinction.
|
||||
4. Preserve an explicitly requested model or existing target. Cite the current official page and state uncertainty about availability, pricing, limits, or account access.
|
||||
|
||||
Pure model selection does not require migration metadata. **Do not run the resolver.**
|
||||
|
||||
Read `references/latest-model.md` only when fetched current official sources cannot answer the question. Disclose that bundled fallback guidance was used and may be outdated.
|
||||
@@ -1,25 +0,0 @@
|
||||
# Official documentation, API references, and ChatGPT Work
|
||||
|
||||
Use this route for OpenAI product or API documentation, examples, citations, ChatGPT Work, learning content, mixed Chat/Work/Codex comparisons, and narrow Codex product documentation. Follow the root skill's official-source order and credential boundary.
|
||||
|
||||
An explicit OpenAI documentation question stays documentation-first even when embedded in a broader repository, Promptfoo, agent-evaluation, `PLANS.md`, frontend, tool-use, image, Realtime API, SDK installation, or streaming-debugging task. Search the exact requested official documentation and open or fetch its relevant page before inspecting local files, drafting a plan, running evals, reading bundled references, or invoking the Codex manual. Then use the fetched official source to complete the requested work.
|
||||
|
||||
## Find the smallest useful source
|
||||
|
||||
1. Search the exact topic with a specific, title-like query containing 2-6 essential terms. Prefer an already-available direct official documentation search and page-retrieval capability; search, then fetch or open the best page or section. Otherwise, immediately use official-domain web search and actually open or fetch the result.
|
||||
2. If the results are noisy, narrow the query. When a plausible official documentation URL is available, open or fetch the page instead of relying on search snippets. Use an already available documentation index only when there is no clear search query.
|
||||
3. For API schemas, required fields, parameters, or endpoint shapes, use an already available OpenAPI or specification capability when it directly resolves the question. Otherwise verify the shape against the fetched official API guide or reference.
|
||||
4. Cite the exact official page supporting each consequential claim. Keep examples minimal, paraphrase instead of quoting at length, and state when official sources do not establish a capability, parameter, price, or availability.
|
||||
|
||||
Preserve an explicitly requested model in the search and answer. Search the requested topic directly for model-specific frontend and tool-use prompting, image input or generation, Realtime voice or translation, official Agents SDK installation, Responses streaming errors, and Codex Goals. A specific Codex feature, error, setting, or requested citation is a narrow documentation lookup, not the broad manual-first exception. Current or latest model recommendations follow the model-selection route and the same official search-and-fetch order.
|
||||
|
||||
## ChatGPT Work and mixed surfaces
|
||||
|
||||
Treat a comparison between Chat, Work, and Codex as ChatGPT Work documentation, not broad Codex self-knowledge. Search `learn.chatgpt.com` and open or fetch the relevant official page. Useful starting pages are:
|
||||
|
||||
- `https://learn.chatgpt.com/docs/use-chatgpt`
|
||||
- `https://learn.chatgpt.com/docs/get-started-with-work`
|
||||
|
||||
If someone simply asks an API question from ChatGPT Work, answer the API question from the relevant API guide. Being in Work does not make it a question about the Work product.
|
||||
|
||||
Separate documented user-facing purposes from unsupported claims about underlying models, hard capability boundaries, file or context inheritance, exact UI labels, account entitlements, and rollout availability. When those details cannot be verified, cite the closest allowed official source and state the uncertainty.
|
||||
@@ -1,115 +0,0 @@
|
||||
## Retrieve the live GPT-6 prompting guidance
|
||||
|
||||
Use already-callable official documentation search and fetch, or immediately use official-domain web search and fetch, to retrieve the live GPT-6 prompting guidance from:
|
||||
|
||||
https://developers.openai.com/api/docs/guides/latest-model/gpt-6-astra.md#prompting-best-practices
|
||||
|
||||
Read only the `## Prompting best practices` section, stopping at the next H2 heading. The URL anchor points to the section visually, but a documentation fetch may return the full page, so explicitly extract only that section.
|
||||
|
||||
Treat the live section as the canonical model-specific prompting guidance. Use the local copy below only when live guidance is unavailable. Keep it identical to the page's `## Prompting best practices` section when refreshing this reference.
|
||||
|
||||
## Prompting best practices
|
||||
|
||||
Use the following prompts as a starting point across the GPT-6 model family. They address behavior observed with GPT-6 Astra; evaluate them with your chosen model and workload.
|
||||
|
||||
### GPT-6 Astra behavior
|
||||
|
||||
- [Initiative and follow-through](#initiative-and-follow-through): The model is designed to be a more effective collaborator and is thus more likely to ask the user a question when additional input could materially change the result. This can cause it to stop when the user may expect it to make reasonable assumptions and persist.
|
||||
- [Instruction following](#instruction-following): GPT-6 Astra is stronger at general instruction following than our previous models, giving you greater control over its behavior. It can be more sensitive to instructions contained in skills and other files, such as `AGENTS.md`. We **strongly recommend** auditing skills and other files accessible to your model for instructions that could influence its behavior.
|
||||
- [Personality and writing style](#personality-and-writing-style): The model tends toward detailed, formatted responses and may use recurring phrases across sessions. Specify the writing style and structure your application needs.
|
||||
- [Subagent delegation](#subagent-delegation): The model may delegate less often than desired for your workflow. Specify when and how much it should use subagents for parallel work.
|
||||
- [Testing and verification](#testing-and-verification): For coding tasks, the model tends to be thorough in testing before considering a task complete. For smaller tasks, this can result in broader tests than the task requires.
|
||||
|
||||
### Initiative and follow-through
|
||||
|
||||
GPT-6 Astra is generally better than GPT-5.6 Sol and earlier models at staying coherent during long tasks. It is also more likely to ask for clarification where earlier models would make assumptions.
|
||||
|
||||
To encourage more autonomous work, start with this prompt:
|
||||
|
||||
```text
|
||||
You should infer the user's intent and task scope from the instructions and prior conversation context. Your job is to bias towards action and carry the user's intended task to completion.
|
||||
|
||||
When the user expresses intent to perform new work or fix an existing issue, persist until the user's intended goal is complete. Progress autonomously towards the user's goal (e.g. creating isolated worktrees / checkouts if needed, resolving merge conflicts, read-only actions, creating draft PRs etc.) unless they are clearly destructive or irreversible.
|
||||
```
|
||||
|
||||
When the user’s intent is unclear, the model is more likely to ask the user for clarification to proceed. Prompt the model to follow through if the user’s prompt implies authorization:
|
||||
|
||||
```text
|
||||
When the user's prompt indicates a request for action, such as "can you...", "I want to...", "help me..." and similar expressions, treat these as instructions to do the work and take action. Do not stop at acknowledging capability (e.g. "Yes…"), proposing a plan, or offering to continue. Do not settle for a partial or "helpful enough" solution that does not fully satisfy the user's task to save time, effort or tokens. If a task requires sustained work, complete all the necessary work until the intended outcome is fulfilled.
|
||||
```
|
||||
|
||||
Prompt the model to ask for approval only after preparing a concrete, reviewable result. This avoids blocking the task before the model has done the work it can, and often leads to quicker task completion.
|
||||
|
||||
```text
|
||||
Before asking the user clarifying questions, you should complete the work that is already authorized from context and necessary to make the proposed action concrete and reviewable. The user should be approving a concrete, reviewable result. For example, before deploying a change, writing to an external application, merging a PR or publishing a site, do all the required work first so that user approval is the final step. You don't need user permission for reversible tasks, read-only actions, reviews or fixes, or anything for which authorization is provided earlier in the session or strongly implied from the task instruction.
|
||||
|
||||
Do not introduce unsolicited warnings, disclaimers, approval flows, or safety/compliance checklists due to hypothetical risk.
|
||||
```
|
||||
|
||||
The model also likes to ask non-blocking questions as it’s working by default, so adjust these prompts to match the level of autonomy your application needs.
|
||||
|
||||
### Instruction following
|
||||
|
||||
GPT-6 Astra is better able to follow longer instructions, but can also be more sensitive to information in context. For example, unclear or conflicting guidance in a skill file may cause the model to pause and block work early. Make the priority of user instructions and skills explicit.
|
||||
|
||||
```text
|
||||
The user's instructions take precedence over guidelines provided in a skill. If explicit user instructions conflict with a skill's instructions, prioritize the user's instructions.
|
||||
```
|
||||
|
||||
Asking the model to identify the skill and instruction that caused it to pause or change direction can also be effective in providing transparency into model behavior.
|
||||
|
||||
```text
|
||||
If a skill causes you to ask for permission or confirmation, pause, leave requested work unfinished, or diverge from the user's intent, name and link to the exact SKILL.md file you read, quote the relevant instruction, and briefly explain how it applies. Distinguish explicit skill requirements from your interpretation of guidelines.
|
||||
```
|
||||
|
||||
Use this prompt to find silent and conflicting guidance when your application loads many skills and instruction files such as `AGENTS.md`.
|
||||
|
||||
### Personality and writing style
|
||||
|
||||
GPT-6 Astra tends to use lists, tables and Markdown to make responses scannable. If your application needs prose with less formatting, specify that preference.
|
||||
|
||||
```text
|
||||
Default to using clear, concise paragraphs, each developing one main idea. Use lists only when the information is genuinely parallel, sequential, or easier to compare, and avoid nested lists unless the hierarchy cannot be expressed clearly in prose. Use plain, simple language: familiar words, concrete examples, and precise verbs. Prefer active voice and direct statements.
|
||||
|
||||
Make sure to state the main point clearly and early, then develop it with the explanation and detail the reader needs. Let each sentence build on what came before. Develop the points that matter and provide enough support to be useful.
|
||||
```
|
||||
|
||||
For technical communication, the following prompt helps strike a balance between using clear, coherent language while remaining domain appropriate:
|
||||
|
||||
```text
|
||||
Use plain language over jargon, and reference technical details only to the degree that it helps illustrate an idea or your work to the user. Communicate complex concepts in a clear and cohesive manner, and calibrate your writing to the level of background knowledge assumed from the user's prompt and context.
|
||||
```
|
||||
|
||||
To reduce jargon and stock phrases in writing, start with this prompt:
|
||||
|
||||
```text
|
||||
Avoid using slop words or phrases like "Bottom Line:" in conclusions, "delve," "foster," "leverage," "it's worth noting," "importantly," "Question? Answer." or "This isn't about X. It's about Y.", "genuinely" or hyphenated compound descriptions and adjectives. Do not use concluding summary statements such as "In short:..", "The simplest mental model is:...".
|
||||
|
||||
State the intended action directly. Avoid adding what you won't do, what will remain unchanged, or how you'll separate or categorize results. Do not use contrastive framing such as "X, not Y" that introduces an unprompted alternative that the user didn't ask about. Avoid invented compound labels like "exact-head checks" and "editorial-row layouts", vague qualifiers, and canned transitions; use plain verbs and prepositions to state the actual relationship directly.
|
||||
```
|
||||
|
||||
### Subagent delegation
|
||||
|
||||
GPT-6 Astra is trained to be able to divide and delegate work to subagents that work in parallel. If you are implementing a multi-agent system in your harness, use the following prompt to tune how much GPT-6 Astra should delegate work:
|
||||
|
||||
```text
|
||||
If at any point you can parallelize work by delegating tasks to another agent (no matter if you are the root or subagent), you should do so using collaboration tools if it could save time or improve quality.
|
||||
```
|
||||
|
||||
Messages between agents may contain grammar or spacing errors. Use this prompt to make inter-agent messages easier to read:
|
||||
|
||||
```text
|
||||
Messages that you send to other agents and your final answer may be read by a human, so ensure they are legible. Always put proper spaces between words and/or numbers.
|
||||
```
|
||||
|
||||
The model tends to respond well to prompting for how and when it should delegate work to subagents, so tune this behavior to fit with your harness and multi-agent implementation.
|
||||
|
||||
### Testing and verification
|
||||
|
||||
For coding tasks, calibrate how much testing and verification a change requires. This can help avoid unnecessary tests or repeated checks for small changes.
|
||||
|
||||
```text
|
||||
Do not write tests for reversible, low-impact changes that mirror the implementation. If you do choose to verify your work with tests, make sure that the tests are meaningful and necessary to verify implementation.
|
||||
|
||||
Run tests appropriate to the change and complete required checks. Once those pass, broaden or repeat testing only when new changes, failures, or unresolved concerns justify it; otherwise, continue toward completing the task.
|
||||
```
|
||||
@@ -1,23 +0,0 @@
|
||||
# Model upgrade guidance
|
||||
|
||||
Use this file only as a bundled routing fallback when the live migration guide cannot be fetched.
|
||||
|
||||
For latest, current, default, or unspecified-model upgrades:
|
||||
|
||||
1. Follow the platform-specific resolver instructions in `references/model-migration.md`.
|
||||
2. Fetch the returned `migrationGuideUrl` exactly; fetch `promptingGuideUrl` only when prompting guidance or prompt changes are needed.
|
||||
3. Treat the live guides as canonical.
|
||||
4. If remote retrieval fails, disclose that bundled fallback guidance is being used.
|
||||
|
||||
For an explicitly requested GPT-6 model:
|
||||
|
||||
1. Preserve the user's explicit target; do not run the latest-model resolver.
|
||||
2. Fetch the live GPT-6 model guidance:
|
||||
|
||||
https://developers.openai.com/api/docs/guides/latest-model/gpt-6-astra.md
|
||||
|
||||
3. Verify the exact target's current official model page and compatibility rules; family examples do not establish support for every sibling. If availability or compatibility cannot be verified, preserve the requested target and report the blocker instead of substituting a model or implementing an unverified migration.
|
||||
4. Read `references/upgrading-to-gpt-6-astra.md` only for unresolved skill-specific migration judgment.
|
||||
5. Read `references/prompting-guide.md` only when prompt changes are needed.
|
||||
|
||||
For another explicit model target, preserve that target and fetch its current official guidance. Do not reuse another model's defaults, API shapes, or compatibility rules, including Astra-only restrictions for Sol or Luna.
|
||||
@@ -1,236 +0,0 @@
|
||||
# Upgrading to the GPT-6 model family
|
||||
|
||||
Use this guide when the user asks to migrate an existing OpenAI API integration, repository, prompt stack, agent, model router, or model picker to GPT-6 Astra, GPT-6.1 Sol, GPT-6 Sol, or GPT-6 Luna after verifying the target's availability.
|
||||
|
||||
Preserve an explicitly requested target. For an unspecified target, use the live model-selection or migration guidance rather than assuming every workload should use Astra.
|
||||
|
||||
Before changing code, retrieve the current live GPT-6 model guidance using already-callable official documentation search and fetch, or immediately use official-domain web search and fetch:
|
||||
|
||||
https://developers.openai.com/api/docs/guides/latest-model/gpt-6-astra.md
|
||||
|
||||
For prompt changes, also read only the `## Prompting best practices` section from:
|
||||
|
||||
https://developers.openai.com/api/docs/guides/latest-model/gpt-6-astra.md#prompting-best-practices
|
||||
|
||||
Treat live docs as canonical for current model IDs, parameters, limits, pricing, and feature availability. The skill-specific workflow below covers repository inspection, scope preservation, and validation. The fallback after it includes all non-prompting guidance, including access notices, examples, caveats, and `## Migration quickstart`; the full prompting section is in `references/prompting-guide.md`. When refreshing, preserve all guide content unless it is specific to the website rather than useful to the skill, and record any omission. Remove website metadata and component markup while retaining their readable content. Resolve site-relative links against `https://developers.openai.com`. Keep section-only links as local fragments when their intended target exists in the same reference file; use canonical absolute URLs for cross-document or absent targets and explicit fetch/source instructions.
|
||||
|
||||
Verify the exact model, endpoint, service tier, and region; if support is unverified, report the unresolved requirement rather than infer support.
|
||||
|
||||
## Core principle
|
||||
|
||||
Do not perform a blind model-string replacement.
|
||||
|
||||
First preserve the behavior, latency class, cost class, reasoning level, endpoint contract, tool semantics, cache behavior, and output contract of each usage site. Then make the smallest safe migration. Adopt new GPT-6 capabilities only when they solve a measured problem or the user explicitly asks for them.
|
||||
|
||||
Set a supported reasoning effort explicitly to preserve the source model's effective behavior; verify omitted defaults rather than guessing.
|
||||
|
||||
## Migration posture
|
||||
|
||||
Classify every usage site before editing:
|
||||
|
||||
1. `simple Astra migration`
|
||||
- One flagship model usage.
|
||||
- Same endpoint and request shape can remain.
|
||||
- Reasoning effort is explicit or its old effective value is known.
|
||||
- No cache, vision, file, tool, or parser behavior needs implementation changes.
|
||||
2. `tier-aware family migration`
|
||||
- The repository exposes multiple model roles, model choices, fallbacks, routers, pricing data, or capability metadata.
|
||||
- Map each role to a verified suitable target instead of replacing everything with Astra.
|
||||
3. `compatibility migration`
|
||||
- The safe move requires parameter, endpoint, cache, state, tool-loop, or multimodal-detail changes.
|
||||
- Make these changes only when implementation work is inside the user's requested scope. Otherwise report the exact blocker and smallest follow-up.
|
||||
4. `prompt migration`
|
||||
- The API shape can remain, but representative traces show a prompt-specific regression.
|
||||
- Make a surgical prompt edit tied to that failure; do not rewrite a working prompt stack wholesale.
|
||||
- When the task is to update prompting guidance, edit the directly tied prompt surface only. Do not modify runtime request code, model schemas, or tests unless the prompt change requires it.
|
||||
5. `optional feature adoption`
|
||||
- Pro mode, persisted reasoning, explicit caching, Programmatic Tool Calling, or multi-agent behavior is being added deliberately.
|
||||
- Keep this separate from the baseline migration so its effect can be measured.
|
||||
6. `leave unchanged`
|
||||
- Historical examples, documentation about old models, snapshots, fixtures, eval baselines, comparison code, intentionally pinned fallbacks, unsupported providers, or ambiguous usages.
|
||||
|
||||
When intent is unclear, prefer leaving a usage unchanged and list it for confirmation over silently changing its role.
|
||||
|
||||
## Inventory before editing
|
||||
|
||||
Search for more than literal model IDs. Inventory:
|
||||
|
||||
- model strings, aliases, environment variables, CLI flags, config defaults, and deployment settings;
|
||||
- SDK calls to Responses, Chat Completions, Batch, or provider adapters;
|
||||
- reasoning settings, token budgets, sampling settings, and latency timeouts;
|
||||
- function tools, hosted tools, structured outputs, response parsers, and replay logic;
|
||||
- system, developer, user, and tool-description prompts tied to each usage;
|
||||
- routers, fallbacks, model allowlists, enums, regexes, validation schemas, and capability maps;
|
||||
- model picker UI, display labels, descriptions, context limits, pricing metadata, and provider catalogs;
|
||||
- prompt-cache keys, retention options, stable-prefix construction, and cache metrics;
|
||||
- image, PDF, file, OCR, and computer-use inputs;
|
||||
- tests, fixtures, snapshots, evals, analytics labels, billing tables, and docs.
|
||||
|
||||
When changing a default model, search every active default surface: runtime config, environment/config files, setup docs, tests, CLI defaults, and deployment examples. Update them together.
|
||||
|
||||
For each usage site, record:
|
||||
|
||||
- source model and why it appears to be used;
|
||||
- endpoint and SDK/client surface;
|
||||
- prompt surface;
|
||||
- effective reasoning effort, including defaults;
|
||||
- latency, cost, context, and quality role;
|
||||
- tools, structured outputs, caching, state replay, and multimodal inputs;
|
||||
- downstream parsers or user-visible contracts;
|
||||
- migration class and validation plan.
|
||||
|
||||
## Structured outputs, parsers, and tool contracts
|
||||
|
||||
Keep output contracts explicit:
|
||||
|
||||
- preserve JSON schemas, required fields, enums, refusal handling, and parser expectations;
|
||||
- preserve tool names, parameter schemas, call IDs, and retry behavior;
|
||||
- keep citations, evidence fields, or native artifacts when downstream consumers require them;
|
||||
- validate that the final answer still satisfies the contract, not merely that a tool call succeeded.
|
||||
|
||||
Do not fix a failing migration by weakening a schema, deleting required behavior, removing routes, dropping tools, or changing business logic unless the user explicitly asked for that product change.
|
||||
|
||||
## Prompt migration judgment
|
||||
|
||||
After the model and API baseline is working, run representative traces before editing prompts. Change prompts for measured failures, documented migration requirements, or an explicit user request. Read `references/prompting-guide.md` for the exact canonical prompting section when prompt changes are needed.
|
||||
|
||||
## Upgrade workflow
|
||||
|
||||
1. Fetch current live GPT-6 docs. Fetch the Prompting Best Practices section only when prompt changes are needed.
|
||||
2. Inventory every usage site and its adjacent prompt, config, registry, parser, and test surfaces.
|
||||
3. Classify each usage by role and migration class.
|
||||
4. Choose the verified available target by the existing workload's role. Do not infer model availability merely because it appears in this fallback.
|
||||
5. Preserve the old effective reasoning effort explicitly when supported; follow the canonical migration guidance for unsupported settings.
|
||||
6. Run the compatibility gates:
|
||||
- endpoint and SDK support;
|
||||
- Chat Completions plus function tools;
|
||||
- cache topology and cache fields;
|
||||
- context length and long-context cost;
|
||||
- image, PDF, and file detail;
|
||||
- structured outputs and parsers;
|
||||
- Responses state replay and tool continuation;
|
||||
- mixed-model routing and unsupported new fields.
|
||||
7. Apply the smallest safe model, config, registry, and prompt changes.
|
||||
8. Do not add optional Pro, persisted reasoning, PTC, explicit caching, async tools, or multi-agent behavior unless needed and measurable.
|
||||
9. Run existing tests and representative evals.
|
||||
10. Report changed, unchanged, blocked, and confirmation-needed sites separately.
|
||||
|
||||
## Validation matrix
|
||||
|
||||
Prefer a controlled comparison:
|
||||
|
||||
1. old model + old prompt + old settings;
|
||||
2. GPT-6 target + same prompt + preserved effective reasoning;
|
||||
3. GPT-6 target + the smallest prompt or API fix required by a measured failure;
|
||||
4. optional feature treatment, isolated from the baseline.
|
||||
|
||||
Measure what matters for the workflow:
|
||||
|
||||
- task success and user-visible quality;
|
||||
- structured-output validity and parser success;
|
||||
- tool choice, tool arguments, retries, loop count, and completion rate;
|
||||
- TTFT, end-to-end latency, timeout rate, and concurrency behavior;
|
||||
- input, output, reasoning, cached, and cache-write tokens;
|
||||
- total cost per successful task;
|
||||
- long-context, compaction, and replay behavior;
|
||||
- image/PDF token use and visual/OCR accuracy;
|
||||
- completeness, preserved behavior, citations, and validation evidence.
|
||||
|
||||
For model routers and pickers, test at least one representative workload for each intended role against its quality, latency, and cost requirements.
|
||||
|
||||
## Required final report
|
||||
|
||||
Return:
|
||||
|
||||
- `Current usage inventory`: each model site, endpoint, role, prompt surface, and old effective reasoning.
|
||||
- `Target mapping`: the exact requested or resolved model, unchanged, or confirmation-needed, with the reason and any availability or compatibility blocker.
|
||||
- `Changes made`: model strings, reasoning settings, prompts, registries, metadata, tests, and API-shape changes.
|
||||
- `Compatibility checks`: Chat Completions/tools, caching, state replay, multimodal detail, context/cost, schemas, and mixed-model routing.
|
||||
- `Prompt changes`: each surgical edit and the failure mode it addresses.
|
||||
- `Validation`: commands, evals, traces, before/after measurements, and remaining gaps.
|
||||
- `Unchanged sites`: historical, pinned, ambiguous, or intentionally role-specific usages.
|
||||
- `Blockers and open questions`: exact issue, why it is unsafe to guess, and the smallest next step.
|
||||
|
||||
Never say the migration is complete merely because model strings changed. It is complete only when the affected behavior and contracts have been validated or the remaining gaps are stated explicitly.
|
||||
|
||||
Choose a GPT-6 model based on the reasoning your task requires, speed, and cost.
|
||||
|
||||
- [GPT-6 Astra](https://developers.openai.com/api/docs/models/gpt-6-astra)
|
||||
|
||||
**Highest intelligence**
|
||||
|
||||
For the most demanding reasoning, coding, and professional work.
|
||||
|
||||
- [GPT-6.1 Sol](https://developers.openai.com/api/docs/models/gpt-6.1-sol)
|
||||
|
||||
**Balanced speed, cost, and intelligence**
|
||||
|
||||
Near-Astra performance for complex work at a lower cost.
|
||||
|
||||
- [GPT-6 Luna](https://developers.openai.com/api/docs/models/gpt-6-luna)
|
||||
|
||||
**Fastest and most cost-effective**
|
||||
|
||||
Strong performance for focused, high-volume tasks.
|
||||
|
||||
To get started, set `model` in a [Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses) request. If you already use [`gpt-6-sol`](https://developers.openai.com/api/docs/models/gpt-6-sol), review the [migration guidance](#migration-quickstart) before switching to GPT-6.1 Sol.
|
||||
|
||||
### GPT-6 Astra
|
||||
|
||||
GPT-6 Astra is our most intelligent model yet, with state-of-the-art performance in computer use, browsing, software engineering, science, and professional work. It can carry out multi-step workflows across code, browsers, and professional software. In [several evaluations](https://openai.com/index/gpt-6-astra/), Astra achieved stronger results using substantially fewer output tokens. Its estimated API cost per task was lower than earlier models despite its higher per-token pricing.
|
||||
|
||||
GPT-6 Astra is also our most aligned model yet. It excels at exercising care, respecting task boundaries, and communicating transparently. When instructions leave room for interpretation, it uses the context it has to fill in routine gaps and asks focused questions when the answer could change the outcome. It incorporates new requirements, changes course when asked, and answers side questions without losing track of the broader task.
|
||||
|
||||
All GPT-6 Astra users also have access to [Fast mode](https://developers.openai.com/api/docs/guides/fast-mode) and the new [Ultrafast mode](https://developers.openai.com/api/docs/guides/ultrafast-mode) for our fastest API speeds.
|
||||
|
||||
### GPT-6.1 Sol
|
||||
|
||||
Use GPT-6.1 Sol for complex coding, computer use, and professional work when you
|
||||
want near-Astra performance at a lower cost. Compare it with Astra on your tasks
|
||||
to assess the tradeoff between quality and cost.
|
||||
|
||||
Set `reasoning.effort` to `low`, `medium` (default), `high`, `xhigh`, or `max`.
|
||||
Use the Responses API for tool calling. Chat Completions supports requests
|
||||
without tools. The `none` and `minimal` reasoning efforts are not supported.
|
||||
|
||||
See the [model page](https://developers.openai.com/api/docs/models/gpt-6.1-sol) for specifications,
|
||||
pricing, and availability, or [model selection](https://developers.openai.com/api/docs/guides/model-selection#when-to-consider-gpt-61-sol)
|
||||
for guidance on choosing a model.
|
||||
|
||||
## What's new
|
||||
|
||||
- **Async tool calling:** GPT-6 can continue reasoning, call other tools, or answer independent parts of a request while your application runs a tool. Set `async: true` on a function or custom tool and return its result when ready using the original `call_id`. Your application still executes the tool and manages pending work. See [Async tool calling](https://developers.openai.com/api/docs/guides/async-tool-calling) for basic usage and a developer-defined wait-tool pattern.
|
||||
- **Mid-turn steering:** Send additional user instructions while GPT-6 is working, such as a correction or a change in requirements. Over a WebSocket connection, the Responses API preserves completed work and includes the update in a continuation. See [Mid-turn steering](https://developers.openai.com/api/docs/guides/steering) for the event flow and tool-result handling.
|
||||
- **Change reasoning mid-conversation while preserving cache:** Add a `configuration_update` input item to increase reasoning effort for difficult work or reduce it for routine follow-ups without rewriting the original prompt prefix. The updated reasoning effort applies until another `configuration_update` input item overrides it. See [Change reasoning mid-conversation](https://developers.openai.com/api/docs/guides/reasoning#change-reasoning-mid-conversation) for examples and compatibility.
|
||||
- **Misalignment monitoring:** As part of our [strengthened safeguards](https://openai.com/index/path-to-astra/) for GPT-6 Astra, our systems asynchronously monitor for misalignment and trigger alerts when necessary. See [Misalignment monitoring](https://developers.openai.com/api/docs/guides/safety-checks/misalignment-monitoring) for more information.
|
||||
|
||||
GPT-6 also supports the existing API capabilities available with GPT-5.6, including [computer use](https://developers.openai.com/api/docs/guides/tools-computer-use), [Structured Outputs](https://developers.openai.com/api/docs/guides/structured-outputs), [streaming](https://developers.openai.com/api/docs/guides/streaming-responses), [Programmatic Tool Calling](https://developers.openai.com/api/docs/guides/tools-programmatic-tool-calling), [multi-agent orchestration](https://developers.openai.com/api/docs/guides/responses-multi-agent), [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching), [persisted reasoning](https://developers.openai.com/api/docs/guides/reasoning#preserve-reasoning-across-calls), [compaction](https://developers.openai.com/api/docs/guides/compaction), and [pro mode](https://developers.openai.com/api/docs/guides/reasoning#reasoning-mode).
|
||||
|
||||
## Limitations
|
||||
|
||||
- GPT-6 Astra and GPT-6.1 Sol do not support the `none` reasoning effort; GPT-6 Sol and GPT-6 Luna do.
|
||||
- Fast mode is not available with EU data residency for GPT-6 Astra, GPT-6 Sol, or GPT-6 Luna. [Ultrafast mode](https://developers.openai.com/api/docs/guides/ultrafast-mode) supports US data residency and global processing only. It does not support EU or other non-US regional processing endpoints. See [data residency eligibility](https://developers.openai.com/api/docs/guides/your-data#which-models-and-features-are-eligible-for-data-residency).
|
||||
|
||||
## Migration quickstart
|
||||
|
||||
### Migrate with Codex
|
||||
|
||||
Codex can apply the recommended changes in this guide with the [OpenAI Docs skill](https://github.com/openai/codex/tree/main/codex-rs/skills/src/assets/samples/openai-docs).
|
||||
|
||||
```text
|
||||
$openai-docs migrate this project to the GPT-6 model family
|
||||
```
|
||||
|
||||
To use this skill in other coding agents, download it from the [Codex repository](https://github.com/openai/codex/tree/main/codex-rs/skills/src/assets/samples/openai-docs).
|
||||
|
||||
### Update API and model parameters
|
||||
|
||||
Set `model` to `gpt-6-astra`, `gpt-6.1-sol`, or `gpt-6-luna`, then check the following:
|
||||
|
||||
- **Reasoning effort:** Preserve your current effective [reasoning effort](https://developers.openai.com/api/docs/guides/reasoning#reasoning-effort) where supported. GPT-6 Astra and GPT-6.1 Sol do not support `none`; use `low` instead. GPT-6 Sol and GPT-6 Luna support `none`. If your existing request uses `minimal`, start with `low` and compare results on representative tasks. Use `reasoning.effort` in Responses or `reasoning_effort` in Chat Completions.
|
||||
- **Tool calling:** Use the [Responses API](https://developers.openai.com/api/docs/guides/migrate-to-responses#migrating-from-chat-completions). GPT-6 Astra and GPT-6.1 Sol support Chat Completions, but tool calling requires Responses. GPT-6 Sol and GPT-6 Luna support function calling in Chat Completions only with `reasoning_effort: "none"`. Use Responses for reasoning with tools.
|
||||
- **Unsupported parameters:** When reasoning effort is not `none`, remove `temperature`, `top_p`, and `top_logprobs`. For Chat Completions, also remove `logprobs`. For Responses, remove `message.output_text.logprobs` from `include`.
|
||||
- **Data residency:** Fast mode is not available with EU data residency for GPT-6 Astra, GPT-6 Sol, or GPT-6 Luna. [Ultrafast mode](https://developers.openai.com/api/docs/guides/ultrafast-mode) supports US data residency and global processing only. It does not support EU or other non-US regional processing endpoints. Fast mode for GPT-6 Astra does not include a latency SLA. See [Fast mode compatibility](https://developers.openai.com/api/docs/guides/fast-mode#is-fast-mode-compatible-with-data-residency-zero-data-retention-and-a-baa).
|
||||
- **Changing reasoning effort:** If your application changes effort between responses, use `configuration_update` items in standard, single-agent requests. Keep request-level `reasoning.effort` unchanged to preserve the prompt prefix for caching. Check the [compatibility limits](https://developers.openai.com/api/docs/guides/reasoning#change-reasoning-mid-conversation) before adopting this feature.
|
||||
- **Prompt caching:** When migrating from GPT-5.5 or earlier, replace `prompt_cache_retention` with `prompt_cache_options.ttl` set to `"30m"`. Review the [prompt caching changes](https://developers.openai.com/api/docs/guides/prompt-caching#summary-of-model-differences), including cache boundaries and cache-write billing.
|
||||
- **Unnecessary approval pauses:** If you run into issues where the model keeps asking for approval before proceeding, use the [initiative and follow-through guidance](https://developers.openai.com/api/docs/guides/latest-model/gpt-6-astra.md#initiative-and-follow-through) to prompt for more autonomous execution. See the rest of [Prompting best practices](https://developers.openai.com/api/docs/guides/latest-model/gpt-6-astra.md#prompting-best-practices) for guidance on instruction following, writing style, subagent delegation, and testing.
|
||||
@@ -1,580 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
import {
|
||||
access,
|
||||
mkdir,
|
||||
readFile,
|
||||
rename,
|
||||
rm,
|
||||
stat,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import process from "node:process";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { inspect, promisify } from "node:util";
|
||||
|
||||
const DEFAULT_MANUAL_URL =
|
||||
"https://developers.openai.com/codex/codex-manual.md";
|
||||
const DEFAULT_CACHE_DIR_NAME = "openai-docs-cache";
|
||||
const CACHE_FILE_NAME = "codex-manual.md";
|
||||
const OUTLINE_FILE_NAME = "codex-manual.outline.md";
|
||||
const HASH_HEADER = "x-content-sha256";
|
||||
const USER_AGENT = "codex-openai-docs";
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
class ManualFetchError extends Error {
|
||||
constructor(message, options) {
|
||||
super(message, options);
|
||||
this.name = "ManualFetchError";
|
||||
}
|
||||
}
|
||||
|
||||
const sha256 = (value) => createHash("sha256").update(value).digest("hex");
|
||||
|
||||
const withTimeout = async (promiseFactory, timeoutMs) => {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
||||
try {
|
||||
return await promiseFactory(controller.signal);
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
};
|
||||
|
||||
const proxyConfigured = () =>
|
||||
process.env.HTTP_PROXY ||
|
||||
process.env.HTTPS_PROXY ||
|
||||
process.env.http_proxy ||
|
||||
process.env.https_proxy;
|
||||
|
||||
const responseHeaders = (headers) => ({
|
||||
get(name) {
|
||||
return headers.get(name.toLowerCase()) ?? null;
|
||||
},
|
||||
});
|
||||
|
||||
const makeResponse = ({ body, headers, status }) => ({
|
||||
headers: responseHeaders(headers),
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
async text() {
|
||||
return body;
|
||||
},
|
||||
});
|
||||
|
||||
const parseCurlHeaders = (rawHeaders) => {
|
||||
const normalized = rawHeaders.replace(/\r\n/g, "\n").trim();
|
||||
const blocks = normalized.split(/\n\n+/).filter(Boolean);
|
||||
const headerBlock = [...blocks]
|
||||
.reverse()
|
||||
.find((block) => block.startsWith("HTTP/"));
|
||||
|
||||
if (!headerBlock) {
|
||||
throw new ManualFetchError("curl did not return HTTP response headers.");
|
||||
}
|
||||
|
||||
const [statusLine, ...lines] = headerBlock.split("\n");
|
||||
const statusMatch = /^HTTP\/\S+\s+(\d{3})/.exec(statusLine);
|
||||
if (!statusMatch) {
|
||||
throw new ManualFetchError(
|
||||
`Could not parse HTTP status from curl response: ${statusLine}`,
|
||||
);
|
||||
}
|
||||
|
||||
const headers = new Map();
|
||||
lines.forEach((line) => {
|
||||
const separator = line.indexOf(":");
|
||||
if (separator === -1) return;
|
||||
const name = line.slice(0, separator).trim().toLowerCase();
|
||||
const value = line.slice(separator + 1).trim();
|
||||
headers.set(name, value);
|
||||
});
|
||||
|
||||
return {
|
||||
headers,
|
||||
status: Number(statusMatch[1]),
|
||||
};
|
||||
};
|
||||
|
||||
const tempFilePath = (cacheDir, suffix) =>
|
||||
path.join(
|
||||
cacheDir,
|
||||
`.fetch-codex-manual-${process.pid}-${Date.now()}-${Math.random()
|
||||
.toString(16)
|
||||
.slice(2)}${suffix}`,
|
||||
);
|
||||
|
||||
const requestManualWithCurl = async (url, { cacheDir, method, timeoutMs }) => {
|
||||
const headerPath = tempFilePath(cacheDir, ".headers");
|
||||
const bodyPath = tempFilePath(cacheDir, ".body");
|
||||
const curlNames =
|
||||
process.platform === "win32" ? ["curl.exe", "curl"] : ["curl"];
|
||||
const args = [
|
||||
"--silent",
|
||||
"--show-error",
|
||||
"--location",
|
||||
"--dump-header",
|
||||
headerPath,
|
||||
"--output",
|
||||
bodyPath,
|
||||
"--user-agent",
|
||||
USER_AGENT,
|
||||
"--max-time",
|
||||
String(Math.max(1, Math.ceil(timeoutMs / 1000))),
|
||||
];
|
||||
|
||||
if (method === "HEAD") {
|
||||
args.push("--head");
|
||||
} else {
|
||||
args.push("--request", method);
|
||||
}
|
||||
args.push(url);
|
||||
|
||||
let lastError;
|
||||
for (const curlName of curlNames) {
|
||||
try {
|
||||
await execFileAsync(curlName, args, { windowsHide: true });
|
||||
const [rawHeaders, body] = await Promise.all([
|
||||
readFile(headerPath, "utf8"),
|
||||
readFile(bodyPath, "utf8"),
|
||||
]);
|
||||
const { headers, status } = parseCurlHeaders(rawHeaders);
|
||||
return makeResponse({ body, headers, status });
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (error?.code !== "ENOENT") break;
|
||||
} finally {
|
||||
await Promise.all([
|
||||
rm(headerPath, { force: true }),
|
||||
rm(bodyPath, { force: true }),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
if (lastError?.code === "ENOENT") {
|
||||
throw new ManualFetchError("curl is unavailable in this environment.", {
|
||||
cause: lastError,
|
||||
});
|
||||
}
|
||||
throw new ManualFetchError(`${method} ${url} could not be fetched.`, {
|
||||
cause: lastError,
|
||||
});
|
||||
};
|
||||
|
||||
const requestManualWithFetch = async (url, { method, timeoutMs }) => {
|
||||
if (typeof fetch !== "function") {
|
||||
throw new ManualFetchError(
|
||||
"Native fetch is unavailable in this Node runtime.",
|
||||
);
|
||||
}
|
||||
|
||||
return withTimeout(async (signal) => {
|
||||
const response = await fetch(url, {
|
||||
method,
|
||||
headers: { "User-Agent": USER_AGENT },
|
||||
signal,
|
||||
});
|
||||
if (!response.ok || method === "HEAD") return response;
|
||||
// Keep body reads inside both the timeout and transport fallback.
|
||||
return makeResponse({
|
||||
body: await response.text(),
|
||||
headers: response.headers,
|
||||
status: response.status,
|
||||
});
|
||||
}, timeoutMs);
|
||||
};
|
||||
|
||||
const requestManual = async (url, { cacheDir, method, timeoutMs }) => {
|
||||
const preferCurl = Boolean(proxyConfigured()) || typeof fetch !== "function";
|
||||
const transports = preferCurl
|
||||
? [
|
||||
() => requestManualWithCurl(url, { cacheDir, method, timeoutMs }),
|
||||
() => requestManualWithFetch(url, { method, timeoutMs }),
|
||||
]
|
||||
: [
|
||||
() => requestManualWithFetch(url, { method, timeoutMs }),
|
||||
() => requestManualWithCurl(url, { cacheDir, method, timeoutMs }),
|
||||
];
|
||||
|
||||
let lastError;
|
||||
for (const transport of transports) {
|
||||
try {
|
||||
const response = await transport();
|
||||
if (!response.ok) {
|
||||
throw new ManualFetchError(
|
||||
`${method} ${url} failed with HTTP ${response.status}.`,
|
||||
);
|
||||
}
|
||||
return response;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
|
||||
throw new ManualFetchError(`${method} ${url} could not be fetched.`, {
|
||||
cause: lastError,
|
||||
});
|
||||
};
|
||||
|
||||
const readHeaderSha = (response) => {
|
||||
const value = response.headers.get(HASH_HEADER);
|
||||
if (!value || !/^[a-f0-9]{64}$/i.test(value)) {
|
||||
throw new ManualFetchError(`Manual response is missing ${HASH_HEADER}.`);
|
||||
}
|
||||
return value.toLowerCase();
|
||||
};
|
||||
|
||||
const nearestExistingParent = async (target) => {
|
||||
let current = target;
|
||||
while (true) {
|
||||
try {
|
||||
const info = await stat(current);
|
||||
return info.isDirectory() ? current : null;
|
||||
} catch (error) {
|
||||
if (error?.code !== "ENOENT") return null;
|
||||
}
|
||||
|
||||
const parent = path.dirname(current);
|
||||
if (parent === current) return null;
|
||||
current = parent;
|
||||
}
|
||||
};
|
||||
|
||||
const usableCacheDir = async (cacheDir) => {
|
||||
if (!cacheDir) return null;
|
||||
const resolved = path.resolve(cacheDir);
|
||||
|
||||
const parent = await nearestExistingParent(resolved);
|
||||
if (!parent) return null;
|
||||
|
||||
try {
|
||||
await access(parent, fsConstants.W_OK | fsConstants.X_OK);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
return resolved;
|
||||
};
|
||||
|
||||
const defaultCacheDirCandidates = () => {
|
||||
const candidates = [];
|
||||
const seen = new Set();
|
||||
const pushCandidate = (candidate) => {
|
||||
if (!candidate || seen.has(candidate)) return;
|
||||
seen.add(candidate);
|
||||
candidates.push(candidate);
|
||||
};
|
||||
|
||||
[process.env.TMPDIR, process.env.TEMP, process.env.TMP].forEach((baseDir) => {
|
||||
if (baseDir) {
|
||||
pushCandidate(path.join(baseDir, DEFAULT_CACHE_DIR_NAME));
|
||||
}
|
||||
});
|
||||
|
||||
if (process.platform !== "win32") {
|
||||
pushCandidate(`/private/tmp/${DEFAULT_CACHE_DIR_NAME}`);
|
||||
pushCandidate(`/tmp/${DEFAULT_CACHE_DIR_NAME}`);
|
||||
}
|
||||
|
||||
return candidates;
|
||||
};
|
||||
|
||||
const resolveCacheDir = async (cacheDir) => {
|
||||
if (cacheDir) {
|
||||
return usableCacheDir(cacheDir);
|
||||
}
|
||||
|
||||
for (const candidate of defaultCacheDirCandidates()) {
|
||||
const usable = await usableCacheDir(candidate);
|
||||
if (usable) return usable;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const cacheFilePath = (cacheDir) => path.join(cacheDir, CACHE_FILE_NAME);
|
||||
|
||||
const outlineFilePath = (cacheDir) => path.join(cacheDir, OUTLINE_FILE_NAME);
|
||||
|
||||
const manualLines = (manual) => {
|
||||
const lines = manual.replace(/\r\n/g, "\n").split("\n");
|
||||
if (lines[lines.length - 1] === "") lines.pop();
|
||||
return lines;
|
||||
};
|
||||
|
||||
const sectionTitle = (rawTitle) =>
|
||||
rawTitle
|
||||
.replace(/\s+#+\s*$/, "")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
|
||||
const buildOutline = (manual) => {
|
||||
const lines = manualLines(manual);
|
||||
const headings = [];
|
||||
let inFence = false;
|
||||
|
||||
lines.forEach((line, index) => {
|
||||
if (/^\s*(```|~~~)/.test(line)) {
|
||||
inFence = !inFence;
|
||||
return;
|
||||
}
|
||||
if (inFence) return;
|
||||
|
||||
const match = /^(#{1,6})\s+(.+?)\s*$/.exec(line);
|
||||
if (!match) return;
|
||||
|
||||
const level = match[1].length;
|
||||
if (level < 2 || level > 3) return;
|
||||
|
||||
headings.push({
|
||||
level,
|
||||
title: sectionTitle(match[2]),
|
||||
startLine: index + 1,
|
||||
endLine: lines.length,
|
||||
});
|
||||
});
|
||||
|
||||
for (let index = 0; index < headings.length; index += 1) {
|
||||
const heading = headings[index];
|
||||
const nextPeer = headings
|
||||
.slice(index + 1)
|
||||
.find((candidate) => candidate.level <= heading.level);
|
||||
if (nextPeer) {
|
||||
heading.endLine = nextPeer.startLine - 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (headings.length === 0) {
|
||||
return {
|
||||
headingCount: 0,
|
||||
lineCount: lines.length,
|
||||
text: "No markdown headings found.",
|
||||
};
|
||||
}
|
||||
|
||||
const minLevel = Math.min(...headings.map((heading) => heading.level));
|
||||
return {
|
||||
headingCount: headings.length,
|
||||
lineCount: lines.length,
|
||||
text: headings
|
||||
.map((heading) => {
|
||||
const indent = " ".repeat(heading.level - minLevel);
|
||||
return `${indent}- ${heading.title} (lines ${heading.startLine}-${heading.endLine})`;
|
||||
})
|
||||
.join("\n"),
|
||||
};
|
||||
};
|
||||
|
||||
const outlineMarkdown = (outline) =>
|
||||
`# Codex Manual Outline\n\n${outline.text}\n`;
|
||||
|
||||
const manualStatusLine = (status) =>
|
||||
status.cacheStatus === "hit"
|
||||
? "Manual status: local manual was already current."
|
||||
: "Manual status: local manual was updated.";
|
||||
|
||||
const formatResult = ({ status, outlineText }) =>
|
||||
[
|
||||
`Manual path: ${status.manualPath}`,
|
||||
`Outline path: ${status.outlinePath}`,
|
||||
manualStatusLine(status),
|
||||
"",
|
||||
outlineText,
|
||||
].join("\n");
|
||||
|
||||
const readCachedManual = async (cacheDir, expectedSha256) => {
|
||||
try {
|
||||
const manual = await readFile(cacheFilePath(cacheDir), "utf8");
|
||||
return sha256(manual) === expectedSha256 ? manual : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const writeCachedManual = async (cacheDir, manual) => {
|
||||
await mkdir(cacheDir, { recursive: true });
|
||||
const tmpPath = tempFilePath(cacheDir, `.${CACHE_FILE_NAME}.tmp`);
|
||||
await writeFile(tmpPath, manual, "utf8");
|
||||
await rename(tmpPath, cacheFilePath(cacheDir));
|
||||
};
|
||||
|
||||
const writeOutline = async (cacheDir, outlineText) => {
|
||||
await mkdir(cacheDir, { recursive: true });
|
||||
const tmpPath = tempFilePath(cacheDir, `.${OUTLINE_FILE_NAME}.tmp`);
|
||||
await writeFile(tmpPath, outlineText, "utf8");
|
||||
await rename(tmpPath, outlineFilePath(cacheDir));
|
||||
};
|
||||
|
||||
const fetchCodexManual = async ({
|
||||
manualUrl = DEFAULT_MANUAL_URL,
|
||||
cacheDir,
|
||||
timeoutMs = 30000,
|
||||
} = {}) => {
|
||||
const resolvedCacheDir = await resolveCacheDir(cacheDir);
|
||||
if (!resolvedCacheDir) {
|
||||
throw new ManualFetchError(
|
||||
"Manual cache directory is unavailable; pass --cache-dir to override or use OpenAI Docs MCP fallback.",
|
||||
);
|
||||
}
|
||||
await mkdir(resolvedCacheDir, { recursive: true });
|
||||
|
||||
const headResponse = await requestManual(manualUrl, {
|
||||
cacheDir: resolvedCacheDir,
|
||||
method: "HEAD",
|
||||
timeoutMs,
|
||||
});
|
||||
const expectedSha256 = readHeaderSha(headResponse);
|
||||
const manualPath = cacheFilePath(resolvedCacheDir);
|
||||
const outlinePath = outlineFilePath(resolvedCacheDir);
|
||||
const checkedAt = new Date().toISOString();
|
||||
|
||||
let manualText = await readCachedManual(resolvedCacheDir, expectedSha256);
|
||||
const cacheStatus = manualText === null ? "updated" : "hit";
|
||||
if (manualText === null) {
|
||||
const getResponse = await requestManual(manualUrl, {
|
||||
cacheDir: resolvedCacheDir,
|
||||
method: "GET",
|
||||
timeoutMs,
|
||||
});
|
||||
const getHeaderSha256 = readHeaderSha(getResponse);
|
||||
if (getHeaderSha256 !== expectedSha256) {
|
||||
throw new ManualFetchError(
|
||||
`${HASH_HEADER} changed between HEAD and GET for ${manualUrl}.`,
|
||||
);
|
||||
}
|
||||
|
||||
manualText = await getResponse.text();
|
||||
if (sha256(manualText) !== expectedSha256) {
|
||||
throw new ManualFetchError(
|
||||
`${HASH_HEADER} did not match the fetched manual body for ${manualUrl}.`,
|
||||
);
|
||||
}
|
||||
|
||||
await writeCachedManual(resolvedCacheDir, manualText);
|
||||
}
|
||||
|
||||
const outline = buildOutline(manualText);
|
||||
const outlineText = outlineMarkdown(outline);
|
||||
await writeOutline(resolvedCacheDir, outlineText);
|
||||
|
||||
return {
|
||||
outlineText,
|
||||
status: {
|
||||
manualUrl,
|
||||
headerSha256: expectedSha256,
|
||||
fetchedManualSha256: expectedSha256,
|
||||
manualHashMatches: true,
|
||||
cacheStatus,
|
||||
cacheDir: resolvedCacheDir,
|
||||
manualPath,
|
||||
outlinePath,
|
||||
checkedAt,
|
||||
lineCount: outline.lineCount,
|
||||
headingCount: outline.headingCount,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const parseArgs = (argv) => {
|
||||
const args = {
|
||||
manualUrl: DEFAULT_MANUAL_URL,
|
||||
cacheDir: undefined,
|
||||
timeoutMs: 30000,
|
||||
statusJson: false,
|
||||
};
|
||||
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index];
|
||||
if (arg === "--manual-url") {
|
||||
args.manualUrl = argv[++index];
|
||||
} else if (arg === "--cache-dir") {
|
||||
args.cacheDir = argv[++index];
|
||||
} else if (arg === "--timeout-ms") {
|
||||
args.timeoutMs = Number(argv[++index]);
|
||||
} else if (arg === "--status-json") {
|
||||
args.statusJson = true;
|
||||
} else {
|
||||
throw new ManualFetchError(`Unknown argument: ${arg}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (!args.manualUrl) {
|
||||
throw new ManualFetchError("--manual-url cannot be empty.");
|
||||
}
|
||||
if (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0) {
|
||||
throw new ManualFetchError("--timeout-ms must be a positive number.");
|
||||
}
|
||||
|
||||
return args;
|
||||
};
|
||||
|
||||
const main = async () => {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
const { outlineText, status } = await fetchCodexManual(args);
|
||||
|
||||
process.stdout.write(formatResult({ status, outlineText }));
|
||||
|
||||
if (args.statusJson) {
|
||||
console.error(JSON.stringify(status));
|
||||
}
|
||||
};
|
||||
|
||||
const envProxyHint = () => {
|
||||
if (proxyConfigured()) {
|
||||
return "Hint: proxy env vars are present. This helper prefers `curl` in proxied sessions; if requests still fail, verify `curl` is installed and the proxy configuration is valid.";
|
||||
}
|
||||
if (typeof fetch !== "function") {
|
||||
return "Hint: native fetch is unavailable in this Node runtime. Install `curl` or use a newer Node version to fetch the manual.";
|
||||
}
|
||||
if (process.platform === "win32") {
|
||||
return "Hint: on Windows, pass a cache dir under `%TEMP%` or `%TMP%`.";
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const formatErrorDetails = (error) => {
|
||||
const details = inspect(error, {
|
||||
breakLength: 120,
|
||||
colors: false,
|
||||
compact: false,
|
||||
depth: 8,
|
||||
});
|
||||
if (!error?.cause) {
|
||||
return details;
|
||||
}
|
||||
|
||||
return `${details}\n\nCause:\n${inspect(error.cause, {
|
||||
breakLength: 120,
|
||||
colors: false,
|
||||
compact: false,
|
||||
depth: 8,
|
||||
})}`;
|
||||
};
|
||||
|
||||
const isCliEntrypoint = () => {
|
||||
const entrypoint = process.argv[1];
|
||||
if (!entrypoint) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return pathToFileURL(entrypoint).href === import.meta.url;
|
||||
};
|
||||
|
||||
if (isCliEntrypoint()) {
|
||||
main().catch((error) => {
|
||||
console.error(`Error: ${error.message}`);
|
||||
const hint = envProxyHint();
|
||||
if (hint) {
|
||||
console.error(hint);
|
||||
}
|
||||
console.error("");
|
||||
console.error("Details:");
|
||||
console.error(formatErrorDetails(error));
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
|
||||
export { DEFAULT_MANUAL_URL, fetchCodexManual };
|
||||
@@ -1,39 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
SCRIPT_PATH="$SCRIPT_DIR/resolve-latest-model-info.cjs"
|
||||
|
||||
is_compatible_node() {
|
||||
"$1" -e 'const major = Number(process.versions.node.split(".")[0]); process.exit(major >= 18 ? 0 : 1)' >/dev/null 2>&1
|
||||
}
|
||||
|
||||
run_if_compatible() {
|
||||
CANDIDATE=$1
|
||||
shift
|
||||
if [ -n "$CANDIDATE" ] && [ -x "$CANDIDATE" ] && is_compatible_node "$CANDIDATE"; then
|
||||
exec "$CANDIDATE" "$SCRIPT_PATH" "$@"
|
||||
fi
|
||||
}
|
||||
|
||||
if [ -n "${NODE:-}" ]; then
|
||||
run_if_compatible "$NODE" "$@"
|
||||
fi
|
||||
|
||||
PATH_NODE=$(command -v node 2>/dev/null || true)
|
||||
if [ -n "$PATH_NODE" ]; then
|
||||
run_if_compatible "$PATH_NODE" "$@"
|
||||
fi
|
||||
|
||||
for CANDIDATE in \
|
||||
"$HOME/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/bin/node" \
|
||||
"$HOME/.cache/codex-runtimes/codex-primary-runtime/dependencies/bin/node" \
|
||||
"/opt/homebrew/bin/node" \
|
||||
"/usr/local/bin/node" \
|
||||
"/usr/bin/node"
|
||||
do
|
||||
run_if_compatible "$CANDIDATE" "$@"
|
||||
done
|
||||
|
||||
echo "No usable Node.js 18+ runtime found for resolve-latest-model-info.cjs" >&2
|
||||
exit 127
|
||||
@@ -1,163 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
// Keep this entrypoint CommonJS-safe when the skill is copied into a type=module repo.
|
||||
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
|
||||
const DEFAULT_URL =
|
||||
"https://developers.openai.com/api/docs/guides/latest-model.md";
|
||||
const DEFAULT_BASE_URL = "https://developers.openai.com";
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = {
|
||||
source: process.env.LATEST_MODEL_URL || DEFAULT_URL,
|
||||
baseUrl: process.env.LATEST_MODEL_BASE_URL || DEFAULT_BASE_URL,
|
||||
};
|
||||
|
||||
for (let i = 2; i < argv.length; i += 1) {
|
||||
const arg = argv[i];
|
||||
if (arg === "--source" || arg === "--url") {
|
||||
args.source = argv[i + 1];
|
||||
i += 1;
|
||||
} else if (arg === "--base-url") {
|
||||
args.baseUrl = argv[i + 1];
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return args;
|
||||
}
|
||||
|
||||
async function readSource(source) {
|
||||
if (source.startsWith("file://")) {
|
||||
return fs.readFile(new URL(source), "utf8");
|
||||
}
|
||||
|
||||
if (!/^https?:\/\//.test(source)) {
|
||||
return fs.readFile(path.resolve(source), "utf8");
|
||||
}
|
||||
|
||||
let lastError;
|
||||
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
||||
try {
|
||||
const response = await fetch(source, {
|
||||
headers: { accept: "text/markdown,text/plain,*/*" },
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
// Body failures must be caught by this attempt's retry handler.
|
||||
return await response.text();
|
||||
}
|
||||
|
||||
lastError = new Error(
|
||||
"failed to fetch " + source + ": " + response.status,
|
||||
);
|
||||
if (response.status < 500 && response.status !== 429) {
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
|
||||
if (attempt < 3) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 250 * attempt));
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
function parseIndentedInfo(lines, startIndex) {
|
||||
const info = {};
|
||||
|
||||
for (let i = startIndex + 1; i < lines.length; i += 1) {
|
||||
const line = lines[i];
|
||||
if (!line.trim()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const match = line.match(/^ {2}([A-Za-z][A-Za-z0-9_-]*):\s*(.+?)\s*$/);
|
||||
if (!match) {
|
||||
break;
|
||||
}
|
||||
|
||||
info[match[1]] = match[2].replace(/^["']|["']$/g, "");
|
||||
}
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
function parseFlatInfo(block) {
|
||||
const info = {};
|
||||
|
||||
for (const line of block.split(/\r?\n/)) {
|
||||
const match = line.match(/^\s*([A-Za-z][A-Za-z0-9_-]*):\s*(.+?)\s*$/);
|
||||
if (match) {
|
||||
info[match[1]] = match[2].replace(/^["']|["']$/g, "");
|
||||
}
|
||||
}
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
function extractLatestModelInfo(markdown) {
|
||||
const lines = markdown.split(/\r?\n/);
|
||||
const latestModelInfoIndex = lines.findIndex((line) =>
|
||||
/^latestModelInfo:\s*$/.test(line),
|
||||
);
|
||||
|
||||
if (latestModelInfoIndex >= 0) {
|
||||
return parseIndentedInfo(lines, latestModelInfoIndex);
|
||||
}
|
||||
|
||||
const commentMatch = markdown.match(
|
||||
/<!--\s*latestModelInfo\s*\n([\s\S]*?)\n\s*-->/m,
|
||||
);
|
||||
if (commentMatch) {
|
||||
return parseFlatInfo(commentMatch[1]);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function absoluteUrl(baseUrl, value) {
|
||||
return new URL(value, baseUrl).toString();
|
||||
}
|
||||
|
||||
function normalizeInfo(info, baseUrl) {
|
||||
const model = info?.model?.trim();
|
||||
const migrationGuide = info?.migrationGuide?.trim();
|
||||
const promptingGuide = info?.promptingGuide?.trim();
|
||||
|
||||
if (!model || !migrationGuide || !promptingGuide) {
|
||||
throw new Error(
|
||||
"latestModelInfo must include model, migrationGuide, and promptingGuide",
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
model,
|
||||
migrationGuideUrl: absoluteUrl(baseUrl, migrationGuide),
|
||||
promptingGuideUrl: absoluteUrl(baseUrl, promptingGuide),
|
||||
};
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const { source, baseUrl } = parseArgs(process.argv);
|
||||
const markdown = await readSource(source);
|
||||
const info = extractLatestModelInfo(markdown);
|
||||
|
||||
if (!info) {
|
||||
throw new Error(`latestModelInfo block not found in ${source}`);
|
||||
}
|
||||
|
||||
process.stdout.write(
|
||||
`${JSON.stringify(normalizeInfo(info, baseUrl), null, 2)}\n`,
|
||||
);
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,202 +0,0 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,58 +0,0 @@
|
||||
---
|
||||
name: skill-installer
|
||||
description: Install Codex skills into $CODEX_HOME/skills from a curated list or a GitHub repo path. Use when a user asks to list installable skills, install a curated skill, or install a skill from another repo (including private repos).
|
||||
metadata:
|
||||
short-description: Install curated skills from openai/skills or other repos
|
||||
---
|
||||
|
||||
# Skill Installer
|
||||
|
||||
Helps install skills. By default these are from https://github.com/openai/skills/tree/main/skills/.curated, but users can also provide other locations. Experimental skills live in https://github.com/openai/skills/tree/main/skills/.experimental and can be installed the same way.
|
||||
|
||||
Use the helper scripts based on the task:
|
||||
- List skills when the user asks what is available, or if the user uses this skill without specifying what to do. Default listing is `.curated`, but you can pass `--path skills/.experimental` when they ask about experimental skills.
|
||||
- Install from the curated list when the user provides a skill name.
|
||||
- Install from another repo when the user provides a GitHub repo/path (including private repos).
|
||||
|
||||
Install skills with the helper scripts.
|
||||
|
||||
## Communication
|
||||
|
||||
When listing skills, output approximately as follows, depending on the context of the user's request. If they ask about experimental skills, list from `.experimental` instead of `.curated` and label the source accordingly:
|
||||
"""
|
||||
Skills from {repo}:
|
||||
1. skill-1
|
||||
2. skill-2 (already installed)
|
||||
3. ...
|
||||
Which ones would you like installed?
|
||||
"""
|
||||
|
||||
After installing a skill, tell the user it will be available on their next turn.
|
||||
|
||||
## Scripts
|
||||
|
||||
All of these scripts use network, so when running in the sandbox, request escalation when running them.
|
||||
|
||||
- `scripts/list-skills.py` (prints skills list with installed annotations)
|
||||
- `scripts/list-skills.py --format json`
|
||||
- Example (experimental list): `scripts/list-skills.py --path skills/.experimental`
|
||||
- `scripts/install-skill-from-github.py --repo <owner>/<repo> --path <path/to/skill> [<path/to/skill> ...]`
|
||||
- `scripts/install-skill-from-github.py --url https://github.com/<owner>/<repo>/tree/<ref>/<path>`
|
||||
- Example (experimental skill): `scripts/install-skill-from-github.py --repo openai/skills --path skills/.experimental/<skill-name>`
|
||||
|
||||
## Behavior and Options
|
||||
|
||||
- Defaults to direct download for public GitHub repos.
|
||||
- If download fails with auth/permission errors, falls back to git sparse checkout.
|
||||
- Aborts if the destination skill directory already exists.
|
||||
- Installs into `$CODEX_HOME/skills/<skill-name>` (defaults to `~/.codex/skills`).
|
||||
- Multiple `--path` values install multiple skills in one run, each named from the path basename unless `--name` is supplied.
|
||||
- Options: `--ref <ref>` (default `main`), `--dest <path>`, `--method auto|download|git`.
|
||||
|
||||
## Notes
|
||||
|
||||
- Curated listing is fetched from `https://github.com/openai/skills/tree/main/skills/.curated` via the GitHub API. If it is unavailable, explain the error and exit.
|
||||
- Private GitHub repos can be accessed via existing git credentials or optional `GITHUB_TOKEN`/`GH_TOKEN` for download.
|
||||
- Git fallback tries HTTPS first, then SSH.
|
||||
- The skills at https://github.com/openai/skills/tree/main/skills/.system are preinstalled, so no need to help users install those. If they ask, just explain this. If they insist, you can download and overwrite.
|
||||
- Installed annotations come from `$CODEX_HOME/skills`.
|
||||
@@ -1,5 +0,0 @@
|
||||
interface:
|
||||
display_name: "Skill Installer"
|
||||
short_description: "Install curated skills from openai/skills or other repos"
|
||||
icon_small: "./assets/skill-installer-small.svg"
|
||||
icon_large: "./assets/skill-installer.png"
|
||||
@@ -1,3 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
|
||||
<path fill="#0D0D0D" d="M2.145 3.959a2.033 2.033 0 0 1 2.022-1.824h5.966c.551 0 .997 0 1.357.029.367.03.692.093.993.246l.174.098c.397.243.72.593.932 1.01l.053.114c.116.269.168.557.194.878.03.36.03.805.03 1.357v4.3a2.365 2.365 0 0 1-2.366 2.365h-1.312a2.198 2.198 0 0 1-4.377 0H4.167A2.032 2.032 0 0 1 2.135 10.5V9.333l.004-.088A.865.865 0 0 1 3 8.468l.116-.006A1.135 1.135 0 0 0 3 6.199a.865.865 0 0 1-.865-.864V4.167l.01-.208Zm1.054 1.186a2.198 2.198 0 0 1 0 4.376v.98c0 .534.433.967.968.967H6l.089.004a.866.866 0 0 1 .776.861 1.135 1.135 0 0 0 2.27 0c0-.478.387-.865.865-.865h1.5c.719 0 1.301-.583 1.301-1.301v-4.3c0-.57 0-.964-.025-1.27a1.933 1.933 0 0 0-.09-.493L12.642 4a1.47 1.47 0 0 0-.541-.585l-.102-.056c-.126-.065-.295-.11-.596-.135a17.31 17.31 0 0 0-1.27-.025H4.167a.968.968 0 0 0-.968.968v.978Z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 923 B |
Binary file not shown.
|
Before Width: | Height: | Size: 1.1 KiB |
@@ -1,21 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Shared GitHub helpers for skill install scripts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import urllib.request
|
||||
|
||||
|
||||
def github_request(url: str, user_agent: str) -> bytes:
|
||||
headers = {"User-Agent": user_agent}
|
||||
token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
|
||||
if token:
|
||||
headers["Authorization"] = f"token {token}"
|
||||
req = urllib.request.Request(url, headers=headers)
|
||||
with urllib.request.urlopen(req) as resp:
|
||||
return resp.read()
|
||||
|
||||
|
||||
def github_api_contents_url(repo: str, path: str, ref: str) -> str:
|
||||
return f"https://api.github.com/repos/{repo}/contents/{path}?ref={ref}"
|
||||
@@ -1,355 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Install a skill from a GitHub repo path into $CODEX_HOME/skills."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import zipfile
|
||||
|
||||
from github_utils import github_request
|
||||
|
||||
DEFAULT_REF = "main"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Args:
|
||||
url: str | None = None
|
||||
repo: str | None = None
|
||||
path: list[str] | None = None
|
||||
ref: str = DEFAULT_REF
|
||||
dest: str | None = None
|
||||
name: str | None = None
|
||||
method: str = "auto"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Source:
|
||||
owner: str
|
||||
repo: str
|
||||
ref: str
|
||||
paths: list[str]
|
||||
repo_url: str | None = None
|
||||
|
||||
|
||||
class InstallError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _codex_home() -> str:
|
||||
return os.environ.get("CODEX_HOME", os.path.expanduser("~/.codex"))
|
||||
|
||||
|
||||
def _tmp_root() -> str:
|
||||
base = os.path.join(tempfile.gettempdir(), "codex")
|
||||
os.makedirs(base, exist_ok=True)
|
||||
return base
|
||||
|
||||
|
||||
def _request(url: str) -> bytes:
|
||||
return github_request(url, "codex-skill-install")
|
||||
|
||||
|
||||
def _parse_github_url(url: str, default_ref: str) -> tuple[str, str, str, str | None]:
|
||||
parsed = urllib.parse.urlparse(url)
|
||||
if parsed.netloc != "github.com":
|
||||
raise InstallError("Only GitHub URLs are supported for download mode.")
|
||||
parts = [p for p in parsed.path.split("/") if p]
|
||||
if len(parts) < 2:
|
||||
raise InstallError("Invalid GitHub URL.")
|
||||
owner, repo = parts[0], parts[1]
|
||||
ref = default_ref
|
||||
subpath = ""
|
||||
if len(parts) > 2:
|
||||
if parts[2] in ("tree", "blob"):
|
||||
if len(parts) < 4:
|
||||
raise InstallError("GitHub URL missing ref or path.")
|
||||
ref = parts[3]
|
||||
subpath = "/".join(parts[4:])
|
||||
else:
|
||||
subpath = "/".join(parts[2:])
|
||||
return owner, repo, ref, subpath or None
|
||||
|
||||
|
||||
def _download_repo_zip(owner: str, repo: str, ref: str, dest_dir: str) -> str:
|
||||
zip_url = f"https://codeload.github.com/{owner}/{repo}/zip/{ref}"
|
||||
zip_path = os.path.join(dest_dir, "repo.zip")
|
||||
try:
|
||||
payload = _request(zip_url)
|
||||
except urllib.error.HTTPError as exc:
|
||||
raise InstallError(f"Download failed: HTTP {exc.code}") from exc
|
||||
with open(zip_path, "wb") as file_handle:
|
||||
file_handle.write(payload)
|
||||
with zipfile.ZipFile(zip_path, "r") as zip_file:
|
||||
_safe_extract_zip(zip_file, dest_dir)
|
||||
top_levels = {name.split("/")[0] for name in zip_file.namelist() if name}
|
||||
if not top_levels:
|
||||
raise InstallError("Downloaded archive was empty.")
|
||||
if len(top_levels) != 1:
|
||||
raise InstallError("Unexpected archive layout.")
|
||||
return os.path.join(dest_dir, next(iter(top_levels)))
|
||||
|
||||
|
||||
def _run_git(args: list[str]) -> None:
|
||||
result = subprocess.run(
|
||||
args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise InstallError(result.stderr.strip() or "Git command failed.")
|
||||
|
||||
|
||||
def _safe_extract_zip(zip_file: zipfile.ZipFile, dest_dir: str) -> None:
|
||||
dest_root = os.path.realpath(dest_dir)
|
||||
for info in zip_file.infolist():
|
||||
extracted_path = os.path.realpath(os.path.join(dest_dir, info.filename))
|
||||
if extracted_path == dest_root or extracted_path.startswith(dest_root + os.sep):
|
||||
continue
|
||||
raise InstallError("Archive contains files outside the destination.")
|
||||
zip_file.extractall(dest_dir)
|
||||
|
||||
|
||||
def _validate_relative_path(path: str) -> None:
|
||||
if os.path.isabs(path) or os.path.normpath(path).startswith(".."):
|
||||
raise InstallError("Skill path must be a relative path inside the repo.")
|
||||
|
||||
|
||||
def _validate_skill_name(name: str) -> None:
|
||||
altsep = os.path.altsep
|
||||
if not name or os.path.sep in name or (altsep and altsep in name):
|
||||
raise InstallError("Skill name must be a single path segment.")
|
||||
if name in (".", ".."):
|
||||
raise InstallError("Invalid skill name.")
|
||||
|
||||
|
||||
def _git_sparse_checkout(
|
||||
repo_url: str, ref: str, paths: list[str], dest_dir: str
|
||||
) -> str:
|
||||
repo_dir = os.path.join(dest_dir, "repo")
|
||||
clone_cmd = [
|
||||
"git",
|
||||
"clone",
|
||||
"--filter=blob:none",
|
||||
"--depth",
|
||||
"1",
|
||||
"--sparse",
|
||||
"--single-branch",
|
||||
"--branch",
|
||||
ref,
|
||||
repo_url,
|
||||
repo_dir,
|
||||
]
|
||||
try:
|
||||
_run_git(clone_cmd)
|
||||
except InstallError:
|
||||
_run_git(
|
||||
[
|
||||
"git",
|
||||
"clone",
|
||||
"--filter=blob:none",
|
||||
"--depth",
|
||||
"1",
|
||||
"--sparse",
|
||||
"--single-branch",
|
||||
repo_url,
|
||||
repo_dir,
|
||||
]
|
||||
)
|
||||
_run_git(["git", "-C", repo_dir, "sparse-checkout", "set", *paths])
|
||||
_run_git(["git", "-C", repo_dir, "checkout", ref])
|
||||
return repo_dir
|
||||
|
||||
|
||||
def _validate_skill(path: str, repo_root: str) -> None:
|
||||
resolved_repo_root = os.path.realpath(repo_root)
|
||||
resolved_path = os.path.realpath(path)
|
||||
try:
|
||||
inside_repo = (
|
||||
os.path.commonpath([resolved_repo_root, resolved_path])
|
||||
== resolved_repo_root
|
||||
)
|
||||
except ValueError:
|
||||
inside_repo = False
|
||||
if not inside_repo:
|
||||
raise InstallError("Skill path must be inside the repo.")
|
||||
|
||||
relative_path = os.path.relpath(path, repo_root)
|
||||
current_path = repo_root
|
||||
for component in relative_path.split(os.path.sep):
|
||||
current_path = os.path.join(current_path, component)
|
||||
if os.path.islink(current_path):
|
||||
raise InstallError(
|
||||
f"Symbolic links are not allowed in skills: {os.path.relpath(current_path, repo_root)}"
|
||||
)
|
||||
|
||||
if not os.path.isdir(path):
|
||||
raise InstallError(f"Skill path not found: {path}")
|
||||
skill_md = os.path.join(path, "SKILL.md")
|
||||
if not os.path.isfile(skill_md):
|
||||
raise InstallError("SKILL.md not found in selected skill directory.")
|
||||
|
||||
for root, directories, files in os.walk(path):
|
||||
for name in directories + files:
|
||||
entry_path = os.path.join(root, name)
|
||||
relative_entry = os.path.relpath(entry_path, repo_root)
|
||||
if os.path.islink(entry_path):
|
||||
resolved_entry = os.path.realpath(entry_path)
|
||||
try:
|
||||
inside_skill = (
|
||||
os.path.commonpath([resolved_path, resolved_entry])
|
||||
== resolved_path
|
||||
)
|
||||
except ValueError:
|
||||
inside_skill = False
|
||||
if not inside_skill or not os.path.isfile(resolved_entry):
|
||||
raise InstallError(
|
||||
f"Unsupported symbolic link in skill: {relative_entry}"
|
||||
)
|
||||
continue
|
||||
if not os.path.isdir(entry_path) and not os.path.isfile(entry_path):
|
||||
raise InstallError(f"Unsupported file type in skill: {relative_entry}")
|
||||
|
||||
|
||||
def _copy_skill(src: str, dest_dir: str) -> None:
|
||||
os.makedirs(os.path.dirname(dest_dir), exist_ok=True)
|
||||
if os.path.exists(dest_dir):
|
||||
raise InstallError(f"Destination already exists: {dest_dir}")
|
||||
shutil.copytree(src, dest_dir)
|
||||
|
||||
|
||||
def _build_repo_url(owner: str, repo: str) -> str:
|
||||
return f"https://github.com/{owner}/{repo}.git"
|
||||
|
||||
|
||||
def _build_repo_ssh(owner: str, repo: str) -> str:
|
||||
return f"git@github.com:{owner}/{repo}.git"
|
||||
|
||||
|
||||
def _prepare_repo(source: Source, method: str, tmp_dir: str) -> str:
|
||||
if method in ("download", "auto"):
|
||||
try:
|
||||
return _download_repo_zip(source.owner, source.repo, source.ref, tmp_dir)
|
||||
except InstallError as exc:
|
||||
if method == "download":
|
||||
raise
|
||||
err_msg = str(exc)
|
||||
if "HTTP 401" in err_msg or "HTTP 403" in err_msg or "HTTP 404" in err_msg:
|
||||
pass
|
||||
else:
|
||||
raise
|
||||
if method in ("git", "auto"):
|
||||
repo_url = source.repo_url or _build_repo_url(source.owner, source.repo)
|
||||
try:
|
||||
return _git_sparse_checkout(repo_url, source.ref, source.paths, tmp_dir)
|
||||
except InstallError:
|
||||
repo_url = _build_repo_ssh(source.owner, source.repo)
|
||||
return _git_sparse_checkout(repo_url, source.ref, source.paths, tmp_dir)
|
||||
raise InstallError("Unsupported method.")
|
||||
|
||||
|
||||
def _resolve_source(args: Args) -> Source:
|
||||
if args.url:
|
||||
owner, repo, ref, url_path = _parse_github_url(args.url, args.ref)
|
||||
if args.path is not None:
|
||||
paths = list(args.path)
|
||||
elif url_path:
|
||||
paths = [url_path]
|
||||
else:
|
||||
paths = []
|
||||
if not paths:
|
||||
raise InstallError("Missing --path for GitHub URL.")
|
||||
return Source(owner=owner, repo=repo, ref=ref, paths=paths)
|
||||
|
||||
if not args.repo:
|
||||
raise InstallError("Provide --repo or --url.")
|
||||
if "://" in args.repo:
|
||||
return _resolve_source(
|
||||
Args(url=args.repo, repo=None, path=args.path, ref=args.ref)
|
||||
)
|
||||
|
||||
repo_parts = [p for p in args.repo.split("/") if p]
|
||||
if len(repo_parts) != 2:
|
||||
raise InstallError("--repo must be in owner/repo format.")
|
||||
if not args.path:
|
||||
raise InstallError("Missing --path for --repo.")
|
||||
paths = list(args.path)
|
||||
return Source(
|
||||
owner=repo_parts[0],
|
||||
repo=repo_parts[1],
|
||||
ref=args.ref,
|
||||
paths=paths,
|
||||
)
|
||||
|
||||
|
||||
def _default_dest() -> str:
|
||||
return os.path.join(_codex_home(), "skills")
|
||||
|
||||
|
||||
def _parse_args(argv: list[str]) -> Args:
|
||||
parser = argparse.ArgumentParser(description="Install a skill from GitHub.")
|
||||
parser.add_argument("--repo", help="owner/repo")
|
||||
parser.add_argument("--url", help="https://github.com/owner/repo[/tree/ref/path]")
|
||||
parser.add_argument(
|
||||
"--path",
|
||||
nargs="+",
|
||||
help="Path(s) to skill(s) inside repo",
|
||||
)
|
||||
parser.add_argument("--ref", default=DEFAULT_REF)
|
||||
parser.add_argument("--dest", help="Destination skills directory")
|
||||
parser.add_argument(
|
||||
"--name", help="Destination skill name (defaults to basename of path)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--method",
|
||||
choices=["auto", "download", "git"],
|
||||
default="auto",
|
||||
)
|
||||
return parser.parse_args(argv, namespace=Args())
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
args = _parse_args(argv)
|
||||
try:
|
||||
source = _resolve_source(args)
|
||||
source.ref = source.ref or args.ref
|
||||
if not source.paths:
|
||||
raise InstallError("No skill paths provided.")
|
||||
for path in source.paths:
|
||||
_validate_relative_path(path)
|
||||
dest_root = args.dest or _default_dest()
|
||||
tmp_dir = tempfile.mkdtemp(prefix="skill-install-", dir=_tmp_root())
|
||||
try:
|
||||
repo_root = _prepare_repo(source, args.method, tmp_dir)
|
||||
installed = []
|
||||
for path in source.paths:
|
||||
skill_name = args.name if len(source.paths) == 1 else None
|
||||
skill_name = skill_name or os.path.basename(path.rstrip("/"))
|
||||
_validate_skill_name(skill_name)
|
||||
if not skill_name:
|
||||
raise InstallError("Unable to derive skill name.")
|
||||
dest_dir = os.path.join(dest_root, skill_name)
|
||||
if os.path.exists(dest_dir):
|
||||
raise InstallError(f"Destination already exists: {dest_dir}")
|
||||
skill_src = os.path.join(repo_root, path)
|
||||
_validate_skill(skill_src, repo_root)
|
||||
_copy_skill(skill_src, dest_dir)
|
||||
installed.append((skill_name, dest_dir))
|
||||
finally:
|
||||
if os.path.isdir(tmp_dir):
|
||||
shutil.rmtree(tmp_dir, ignore_errors=True)
|
||||
for skill_name, dest_dir in installed:
|
||||
print(f"Installed {skill_name} to {dest_dir}")
|
||||
return 0
|
||||
except InstallError as exc:
|
||||
print(f"Error: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
@@ -1,106 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""List skills from a GitHub repo path."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
|
||||
from github_utils import github_api_contents_url, github_request
|
||||
|
||||
DEFAULT_REPO = "openai/skills"
|
||||
DEFAULT_PATH = "skills/.curated"
|
||||
DEFAULT_REF = "main"
|
||||
|
||||
|
||||
class ListError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Args(argparse.Namespace):
|
||||
repo: str
|
||||
path: str
|
||||
ref: str
|
||||
format: str
|
||||
|
||||
|
||||
def _request(url: str) -> bytes:
|
||||
return github_request(url, "codex-skill-list")
|
||||
|
||||
|
||||
def _codex_home() -> str:
|
||||
return os.environ.get("CODEX_HOME", os.path.expanduser("~/.codex"))
|
||||
|
||||
|
||||
def _installed_skills() -> set[str]:
|
||||
root = os.path.join(_codex_home(), "skills")
|
||||
if not os.path.isdir(root):
|
||||
return set()
|
||||
entries = set()
|
||||
for name in os.listdir(root):
|
||||
path = os.path.join(root, name)
|
||||
if os.path.isdir(path):
|
||||
entries.add(name)
|
||||
return entries
|
||||
|
||||
|
||||
def _list_skills(repo: str, path: str, ref: str) -> list[str]:
|
||||
api_url = github_api_contents_url(repo, path, ref)
|
||||
try:
|
||||
payload = _request(api_url)
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code == 404:
|
||||
raise ListError(
|
||||
f"Skills path not found: https://github.com/{repo}/tree/{ref}/{path}"
|
||||
) from exc
|
||||
raise ListError(f"Failed to fetch skills: HTTP {exc.code}") from exc
|
||||
data = json.loads(payload.decode("utf-8"))
|
||||
if not isinstance(data, list):
|
||||
raise ListError("Unexpected skills listing response.")
|
||||
skills = [item["name"] for item in data if item.get("type") == "dir"]
|
||||
return sorted(skills)
|
||||
|
||||
|
||||
def _parse_args(argv: list[str]) -> Args:
|
||||
parser = argparse.ArgumentParser(description="List skills.")
|
||||
parser.add_argument("--repo", default=DEFAULT_REPO)
|
||||
parser.add_argument(
|
||||
"--path",
|
||||
default=DEFAULT_PATH,
|
||||
help="Repo path to list (default: skills/.curated)",
|
||||
)
|
||||
parser.add_argument("--ref", default=DEFAULT_REF)
|
||||
parser.add_argument(
|
||||
"--format",
|
||||
choices=["text", "json"],
|
||||
default="text",
|
||||
help="Output format",
|
||||
)
|
||||
return parser.parse_args(argv, namespace=Args())
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
args = _parse_args(argv)
|
||||
try:
|
||||
skills = _list_skills(args.repo, args.path, args.ref)
|
||||
installed = _installed_skills()
|
||||
if args.format == "json":
|
||||
payload = [
|
||||
{"name": name, "installed": name in installed} for name in skills
|
||||
]
|
||||
print(json.dumps(payload))
|
||||
else:
|
||||
for idx, name in enumerate(skills, start=1):
|
||||
suffix = " (already installed)" if name in installed else ""
|
||||
print(f"{idx}. {name}{suffix}")
|
||||
return 0
|
||||
except ListError as exc:
|
||||
print(f"Error: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
@@ -1,137 +0,0 @@
|
||||
"""Local-only regression tests for the bundled skill-installer script.
|
||||
|
||||
Run manually; these tests are not wired into CI:
|
||||
python3 -B -m unittest discover -s codex-rs/skills/tests -p 'test_*.py'
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
INSTALLER = (
|
||||
Path(__file__).resolve().parents[1]
|
||||
/ "src"
|
||||
/ "assets"
|
||||
/ "samples"
|
||||
/ "skill-installer"
|
||||
/ "scripts"
|
||||
/ "install-skill-from-github.py"
|
||||
)
|
||||
|
||||
|
||||
class SkillInstallerSymlinkTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.directory.cleanup)
|
||||
self.root = Path(self.directory.name)
|
||||
self.repository = self.root / "repository"
|
||||
self.skill = self.repository / "skill"
|
||||
self.skill.mkdir(parents=True)
|
||||
(self.skill / "SKILL.md").write_text("Synthetic test skill\n", encoding="utf-8")
|
||||
self.destination = self.root / "installed"
|
||||
|
||||
def create_symlink(self, link: Path, target: Path | str) -> None:
|
||||
try:
|
||||
link.symlink_to(target)
|
||||
except OSError as error:
|
||||
self.skipTest(f"symlinks are unavailable: {error}")
|
||||
|
||||
def run_installer(self) -> subprocess.CompletedProcess[str]:
|
||||
subprocess.run(
|
||||
["git", "init", "--initial-branch=main", str(self.repository)],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(self.repository), "add", "."],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
subprocess.run(
|
||||
[
|
||||
"git",
|
||||
"-C",
|
||||
str(self.repository),
|
||||
"-c",
|
||||
"user.name=Skill Installer Test",
|
||||
"-c",
|
||||
"user.email=skill-installer@example.invalid",
|
||||
"commit",
|
||||
"-m",
|
||||
"synthetic skill fixture",
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
environment = os.environ.copy()
|
||||
python_path = [str(INSTALLER.parent)]
|
||||
if environment.get("PYTHONPATH"):
|
||||
python_path.append(environment["PYTHONPATH"])
|
||||
environment.update(
|
||||
{
|
||||
"GIT_CONFIG_COUNT": "2",
|
||||
"GIT_CONFIG_KEY_0": f"url.{self.repository.as_uri()}.insteadOf",
|
||||
"GIT_CONFIG_VALUE_0": "https://github.com/synthetic/fixture.git",
|
||||
"GIT_CONFIG_KEY_1": "core.symlinks",
|
||||
"GIT_CONFIG_VALUE_1": "true",
|
||||
"GIT_TERMINAL_PROMPT": "0",
|
||||
"PYTHONPATH": os.pathsep.join(python_path),
|
||||
}
|
||||
)
|
||||
return subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"-B",
|
||||
str(INSTALLER),
|
||||
"--repo",
|
||||
"synthetic/fixture",
|
||||
"--path",
|
||||
"skill",
|
||||
"--method",
|
||||
"git",
|
||||
"--dest",
|
||||
str(self.destination),
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
env=environment,
|
||||
)
|
||||
|
||||
def test_rejects_symlink_to_file_outside_skill(self) -> None:
|
||||
outside_file = self.root / "synthetic-secret.txt"
|
||||
outside_file.write_text("synthetic secret\n", encoding="utf-8")
|
||||
self.create_symlink(self.skill / "outside.txt", outside_file)
|
||||
|
||||
result = self.run_installer()
|
||||
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("Unsupported symbolic link", result.stderr)
|
||||
self.assertFalse((self.destination / "skill").exists())
|
||||
|
||||
def test_installs_symlink_to_regular_file_inside_skill(self) -> None:
|
||||
(self.skill / "actual.txt").write_text(
|
||||
"safe skill contents\n", encoding="utf-8"
|
||||
)
|
||||
self.create_symlink(self.skill / "alias.txt", "actual.txt")
|
||||
|
||||
result = self.run_installer()
|
||||
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
installed_alias = self.destination / "skill" / "alias.txt"
|
||||
self.assertFalse(installed_alias.is_symlink())
|
||||
self.assertEqual(
|
||||
installed_alias.read_text(encoding="utf-8"), "safe skill contents\n"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user