@narumitw/pi-codex-imagegen 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 narumiruna
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,127 @@
1
- # Temporary Holding Version
1
+ # 🎨 pi-codex-imagegen
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@narumitw/pi-codex-imagegen)](https://www.npmjs.com/package/@narumitw/pi-codex-imagegen)
4
+ [![Pi extension](https://img.shields.io/badge/Pi-extension-blue)](https://pi.dev)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)
6
+
7
+ Generate images from Pi through the Codex image endpoint, without starting Codex CLI, an agent, or its plugins.
8
+
9
+ > **Experimental:** This uses an internal ChatGPT endpoint, not the public OpenAI Images API. Real account access and transparent output have not been verified. The endpoint can change or reject third-party clients. Do not publish the initial package until the [live checks](./docs/verification.md) pass and publication is explicitly approved.
10
+
11
+ ## ✨ Features
12
+
13
+ - Generate an image manually from a menu or through an opt-in model tool.
14
+ - Write original image bytes to an explicit destination with Pi-native file handling.
15
+ - Cancel owned requests and prevent results from reaching a replaced session.
16
+ - Keep authentication with Pi rather than create another credential store.
17
+
18
+ ## 📦 Install
19
+
20
+ This new package is currently source-only; registry installation is unavailable before its first approved publication. Extensions run with Pi's permissions. Review the source before loading it.
21
+
22
+ From the repository root:
23
+
24
+ ```bash
25
+ npm install
26
+ npm run build
27
+ pi -e ./packages/pi-codex-imagegen
28
+ ```
29
+
30
+ To keep the local checkout installed instead of loading it for one invocation:
31
+
32
+ ```bash
33
+ pi install ./packages/pi-codex-imagegen
34
+ ```
35
+
36
+ The source entrypoint needs no package build. The repository build prepares the Kit library used by the menu.
37
+
38
+ ## 🚀 Quick start
39
+
40
+ Use Pi's `/login` to sign in to the `openai-codex` provider, then open `/codex-imagegen`, choose **Generate Image**, enter a prompt, and enter a destination such as `assets/fox.png`. Choose a new path unless you intend to overwrite an existing file. The saved path is shown with the result.
41
+
42
+ The `openai` provider's login and a login held only by Codex CLI are not substitutes. This extension does not import `~/.codex/auth.json`. Your main Pi model can use another provider. Generation sends the prompt to ChatGPT and can consume account quota.
43
+
44
+ ## 💬 Commands
45
+
46
+ `/codex-imagegen` opens the generation manager, user settings, authentication status, and help. It accepts no arguments and requires TUI mode. RPC receives an unsupported-mode notice; print and JSON receive a command error. No generation is started by these rejection paths.
47
+
48
+ The prompt dialog preserves Pi's native multiline editing and paste behavior. External-editor launch is unavailable in this cancellable dialog because Pi's external-editor handoff cannot be aborted when the dialog is disposed.
49
+
50
+ ## 🛠️ Tools
51
+
52
+ `codex_imagegen` requires `prompt` and `path`, with an optional `transparentBackground` override. It returns the absolute destination path, image content, and structured file details. Image content is handled by Pi's normal tool-result image policy.
53
+
54
+ The tool is **disabled by default**, including codemode, tool search, and nested calls. Enable it explicitly in `/codex-imagegen` → Settings. The manual menu does not require tool enablement. The enabled tool also works in headless modes.
55
+
56
+ `path` uses the same resolution as Pi's `write`: relative paths use the session working directory; absolute paths, `~/`, leading `@`, and file URLs are supported. Shell variables and wildcards are literal, not expanded. There is no default destination or generated filename. No extension is added or changed; the extension does not select or convert the returned image format.
57
+
58
+ ```json
59
+ {
60
+ "prompt": "A simple fox logo",
61
+ "path": "assets/fox.png"
62
+ }
63
+ ```
64
+
65
+ Missing parent directories are created. Existing files are overwritten and symlinks are followed. See [Security and privacy](#-security-and-privacy) before enabling model access.
66
+
67
+ ## ⚙️ Settings
68
+
69
+ User settings live in `<getAgentDir()>/pi-codex-imagegen.json`, normally `~/.pi/agent/pi-codex-imagegen.json`. Edit them through the menu or manually. Menu changes save immediately; Escape does not undo saved changes. Manual edits take effect on the next session start or `/reload`. There are no project overrides or extension-specific environment variables.
70
+
71
+ | Setting | Default | Accepted value |
72
+ | --- | --- | --- |
73
+ | `toolEnabled` | `false` | Boolean; permits model access. |
74
+ | `transparentBackground` | `false` | Boolean; requests transparency by default, with a per-call override. Actual alpha support is provider-dependent. |
75
+
76
+ For example, to enable the tool:
77
+
78
+ ```json
79
+ {
80
+ "toolEnabled": true
81
+ }
82
+ ```
83
+
84
+ Defaults and Status do not create files or directories. Each generation requires an explicit path and can create its parent directories even if generation later fails.
85
+
86
+ Missing settings mean defaults. Invalid files produce a warning or lifecycle error and block settings writes until repaired. Saves preserve unknown fields, use temporary-file-plus-rename publication, and keep the prior effective values after a failed save or application. Settings reads and writes are ordered within one Pi process, not locked across separate Pi processes.
87
+
88
+ Changes require an idle session. Enabling or disabling the tool deliberately changes the model-visible tool set and can affect prompt caching. Ordinary turns do not change tools, prompts, or earlier messages. Manual results append at the conversation tail without starting a model turn.
89
+
90
+ ## 🔒 Security and privacy
91
+
92
+ Only the entered prompt and fixed generation options are sent to `https://chatgpt.com/backend-api/codex/images/generations`. No conversation history, input files, Codex instructions, or plugin settings are sent by this extension. Compatible Pi OAuth supplies the token and account header. Neither credentials nor account identifiers appear in extension settings, status, or errors.
93
+
94
+ The destination is fixed, redirects are rejected, arbitrary provider headers are not forwarded, and no model or API fallback is used. The client identifies itself as `pi-codex-imagegen`. Provider denials are errors, not a reason to bypass policy.
95
+
96
+ Output follows Pi's `write` behavior: it creates parent directories, overwrites existing files, follows symlinks, and uses normal filesystem permissions and umask. Paths are not confined to the repository. A symlink can direct the write outside the project.
97
+
98
+ Returned image data is validated before writing file bytes. Destination checks before generation do not reserve the path against concurrent changes. Writes are not atomic or rolled back: a write failure or cancellation can leave an existing file truncated or partially replaced. Restore overwritten content from version control or a backup.
99
+
100
+ The client uses runtime `fetch` without changing global network settings. Proxy handling depends on the host's HTTP dispatcher; SDK hosts must provide their own network setup. Pi-specific provider or WebSocket proxy routing is not a separate guarantee for this endpoint.
101
+
102
+ ## 🚧 Limitations
103
+
104
+ - Only the legacy `openai-codex` OAuth provider at the canonical ChatGPT backend is accepted. Custom gateways, API keys, generic OpenAI OAuth, and automatic CLI credential reuse are unsupported.
105
+ - The fixed image model is `gpt-image-2`, with quality and size set to `auto`. Image editing, references, masks, batches, and extra model/format controls are unsupported.
106
+ - Authentication waits are limited to 30 seconds; the whole operation has a five-minute HTTP/auth budget. Generation can finish before headers are sent, so headers share that longer budget. The client never retries automatically.
107
+ - Cancelling closes owned HTTP work but cannot guarantee that remote generation stops or quota is refunded. Pi-owned OAuth refresh may finish after this extension stops waiting. A file saved before late cancellation remains on disk.
108
+ - Pi's normal session shutdown aborts work directly. Direct SDK `AgentSession.dispose()` omits that event in the tested runtime; active flows check public context liveness every 100 ms and before subsequent side effects. No poll runs while the extension is idle.
109
+ - Responses are limited to 32 MiB decoded, 16,384 pixels per side, and 16,777,216 pixels total. Static PNG, JPEG, and WebP containers are supported; animations are rejected. Header/container checks are not a complete JPEG/WebP entropy decoder or a codec-security guarantee.
110
+ - Filesystem writes inherit native behavior. Device/pipe targets or stalled filesystems can block, and cancellation is best effort.
111
+ - Inline previews depend on terminal support and Pi image settings. Manual previews can be resized while the original file stays unchanged. Image usage and quota are not reported as an invented Pi dollar cost.
112
+
113
+ See the [architecture](./docs/architecture.md) and [workflow diagrams](./docs/workflows.md) for a visual overview, the [protocol contract](./docs/protocol.md) for implementation evidence, and the [verification guide](./docs/verification.md) for remaining account and physical-terminal checks.
114
+
115
+ ## 🗂️ Package layout
116
+
117
+ - `src/index.ts` forwards the extension factory; descriptive source modules own requests, storage, and UI.
118
+ - `docs/` contains the protocol contract, verification evidence, and release restrictions.
119
+ - `test/` contains repository-only deterministic fixtures and Pi runtime tests; it is not published.
120
+
121
+ ## 🔎 Keywords
122
+
123
+ Pi extension, Codex, image generation, ChatGPT OAuth, terminal UI, image assets.
124
+
125
+ ## 📄 License
126
+
127
+ [MIT](./LICENSE) © narumiruna
@@ -0,0 +1,66 @@
1
+ # Architecture
2
+
3
+ `pi-codex-imagegen` generates images directly from Pi without starting Codex CLI, another agent, or Codex plugins. These diagrams describe the current implementation.
4
+
5
+ > **Experimental:** The extension uses an internal ChatGPT endpoint, not the public OpenAI Images API. Real account access and transparent output have not been verified. See the [verification guide](./verification.md) for the remaining live checks and publication restrictions.
6
+
7
+ ## Component boundaries
8
+
9
+ The manual menu and the optional model tool share one generation pipeline. Pi supplies OAuth authentication; the extension sends the request, validates the returned image, and saves its original bytes.
10
+
11
+ ```mermaid
12
+ flowchart LR
13
+ User["User"] --> Menu["/codex-imagegen<br/>Manual menu"]
14
+ Agent["Pi agent"] --> Tool["codex_imagegen tool<br/>Disabled by default"]
15
+ Menu --> Extension["pi-codex-imagegen"]
16
+ Tool --> Extension
17
+ Auth["Pi ModelRegistry<br/>openai-codex OAuth"] -->|Authentication| Extension
18
+ Extension -->|HTTPS POST| Endpoint["ChatGPT internal endpoint<br/>gpt-image-2"]
19
+ Endpoint -->|Base64 image| Extension
20
+ Extension --> Validation["Validate image"]
21
+ Validation --> File["Save original bytes<br/>to the explicit path"]
22
+ File --> Result["Return path and image content"]
23
+ ```
24
+
25
+ The main Pi model can use another provider. Image generation requires compatible Pi `openai-codex` OAuth; a login held only by Codex CLI is not used.
26
+
27
+ ## Data and cancellation boundaries
28
+
29
+ Only the entered prompt and fixed generation options are sent as the request body. Pi supplies the token and account header. Conversation history, input files, and the destination path are not sent to the image endpoint.
30
+
31
+ ```mermaid
32
+ flowchart LR
33
+ subgraph Local["Local: Pi and extension"]
34
+ Auth["Pi-managed OAuth"]
35
+ Input["Entered prompt<br/>and fixed generation options"]
36
+ Private["Not sent to endpoint:<br/>Conversation history, input files,<br/>and destination path"]
37
+ Validate["Validate returned image"]
38
+ Write["Write image<br/>Overwrite files and follow symlinks"]
39
+ end
40
+ subgraph Remote["Remote: ChatGPT"]
41
+ Endpoint["Fixed HTTPS endpoint<br/>Redirects rejected"]
42
+ Generation["Generate image<br/>May consume account quota"]
43
+ Endpoint --> Generation
44
+ end
45
+ Auth -->|Authentication headers| Endpoint
46
+ Input -->|JSON body| Endpoint
47
+ Generation -->|Image data| Validate
48
+ Validate --> Write
49
+ Cancel["Cancellation, session replacement,<br/>reload, shutdown, or SDK disposal"] --> Stop["Abort owned HTTP work<br/>Reject stale continuations"]
50
+ Stop -.-> Limits["Remote generation may continue<br/>Quota refund is not guaranteed<br/>Existing writes are not rolled back"]
51
+ ```
52
+
53
+ Paths follow Pi's `write` behavior and are not confined to the repository. Symlinks can direct writes outside the project. Cancellation is best effort for filesystem writes, and an image saved before late cancellation remains on disk. Pi-owned OAuth refresh can also finish after the extension stops waiting.
54
+
55
+ ## Implementation references
56
+
57
+ The diagrams map to these package modules:
58
+
59
+ - [`codex-imagegen.ts`](../src/codex-imagegen.ts): entry routes, shared generation pipeline, result publication, and session ownership.
60
+ - [`image-client.ts`](../src/image-client.ts): authentication checks, fixed endpoint, request limits, and HTTP cancellation.
61
+ - [`artifacts.ts`](../src/artifacts.ts): image validation, destination preflight, and binary file writes.
62
+ - [`menu.ts`](../src/menu.ts): manual generation and menu navigation.
63
+
64
+ See the [protocol contract](./protocol.md) for detailed authentication, failure, and storage behavior, and the [README](../README.md) for installation and use.
65
+
66
+ See [Workflows](./workflows.md) for manual generation, model-driven generation, and request ordering.
@@ -0,0 +1,64 @@
1
+ # Codex image protocol contract
2
+
3
+ This is an independent TypeScript implementation of the generation HTTP operation described by OpenAI Codex source. No Codex executable, library, agent, or plugin is bundled or started. The protocol is internal and experimental; offline tests do not establish real account access.
4
+
5
+ ## Source mapping
6
+
7
+ The inspected reference is OpenAI Codex checkout `ffda54f5b8d5595eb0963594de32e206f98cc77f`, licensed under Apache-2.0. No source files are vendored. This implementation uses the protocol fields below rather than porting the Codex runtime.
8
+
9
+ | Reference under `codex-rs/` | TypeScript contract |
10
+ | --- | --- |
11
+ | `model-provider-info/src/lib.rs` | Fixed `https://chatgpt.com/backend-api/codex` root. |
12
+ | `codex-api/src/endpoint/images.rs` | JSON `POST images/generations`; optional `x-codex-imagegen-request-id` response header. |
13
+ | `codex-api/src/images.rs` | Response contains `data[].b64_json`. A URL, file reference, assistant message, or saved path is not image data. |
14
+ | `ext/image-generation/src/tool.rs` | Prompt, `gpt-image-2`, quality `auto`, size `auto`, and background `transparent` or `opaque`. The built-in generation path omits `n`; this client does too and requires exactly one returned image. |
15
+ | `model-provider/src/bearer_auth_provider.rs` | Bearer token and ChatGPT account header. |
16
+ | `ext/image-generation/src/backend.rs` | Originator header. The optional Codex turn metadata is omitted because no Codex turn exists. |
17
+
18
+ Reference source: [OpenAI Codex](https://github.com/openai/codex/tree/ffda54f5b8d5595eb0963594de32e206f98cc77f/codex-rs). Recheck the source when diagnosing upstream changes; do not silently infer a new wire contract from an error example.
19
+
20
+ ## Authentication boundary
21
+
22
+ `image-client.ts` uses only Pi public `ModelRegistry` methods. It checks `openai-codex` provider/model metadata and `isUsingOAuth()` before resolving `getProviderAuth("openai-codex")`. Metadata is checked again after the await, and stale owners cannot send requests.
23
+
24
+ The installed Pi Codex adapter's OAuth implementation resolves its access token as `auth.apiKey`. Its JWT payload contains `payload["https://api.openai.com/auth"].chatgpt_account_id`. The client parses the identifier to create the account header; it does not claim to verify the JWT signature. Pi and the server own authentication and token refresh. API keys and incompatible token shapes fail before HTTP.
25
+
26
+ Accept only the exact canonical provider roots `/backend-api` or `/backend-api/codex`, optionally followed by one slash. A resolved auth base URL must be canonical too. These checks do not select a destination: the actual image URL remains fixed. Provider headers and labels are never copied to requests or error messages.
27
+
28
+ The allowed request headers are `Content-Type`, `Authorization`, `ChatGPT-Account-ID`, `originator`, and an honest `User-Agent`. No Codex client identity, session ID, turn ID, or organization-policy bypass is fabricated.
29
+
30
+ Pi login and Codex CLI login are separate. There is no private credential-file/keyring access or import path. The primary chat model does not have to use Codex. A compatible Pi login still does not prove image entitlement; the server can deny the request.
31
+
32
+ ## Failure and cancellation classes
33
+
34
+ | Class | Behavior |
35
+ | --- | --- |
36
+ | Missing provider/auth, non-OAuth auth, noncanonical root, invalid account claim | Reject with fixed setup guidance; no HTTP request. |
37
+ | Delayed or failed Pi refresh | Bound the wait, redact the error, reject late results. Pi may continue its own refresh. |
38
+ | Owner/caller abort, replacement, reload, shutdown, direct SDK invalidation | Abort owned request work and reject stale continuations before publication. |
39
+ | 401 | Fixed sign-in guidance; no automatic retry. |
40
+ | 403 | Fixed entitlement/policy guidance; no fallback or bypass. |
41
+ | 429 | Fixed quota/rate-limit guidance; no retry loop. |
42
+ | Redirect, other HTTP status, transport loss, timeout | Error; no credential redirect and no generation retry. |
43
+ | Invalid content type, UTF-8, JSON, count, base64, image media, or bounds | Reject before saving; do not interpret URLs or file references. |
44
+ | Missing path, directory destination, or obvious filesystem/permission failure | Reject before HTTP without writing destination bytes. Preflight can create parent directories and is not a reservation against concurrent changes. |
45
+ | Image write failure or cancellation | Report failure; native-style writes can leave truncated or partial files. Do not remove or restore the destination automatically. |
46
+ | Settings write/application failure | Keep the previous effective values and restore the previous settings document; recover the in-process queue. |
47
+
48
+ Do not display raw upstream bodies, credential errors, provider labels, or arbitrary headers. Only a bounded token-like nested image request ID is retained in artifact details. Tool errors and saved-path notices are bounded to Pi's text-output limits even when a filesystem error echoes a very long path; structured path metadata remains complete.
49
+
50
+ ## Bounds and storage
51
+
52
+ Prompt length is at most 32,000 characters. Authentication waits have a 30-second limit, and the total auth/HTTP operation has a five-minute limit. Header waiting can use the remaining total budget because image generation can precede response headers. Readers, listeners, and timers are released on all paths. Local HTTP tests synchronize on request and abort callbacks rather than sleeps.
53
+
54
+ The JSON body limit is the canonical base64 length of a 32 MiB image plus 64 KiB of metadata. A growable bounded buffer avoids unbounded per-chunk overhead. Artifact decoding requires canonical padded base64 and bounded image dimensions. PNG validation includes container/CRC and bounded raster checks; JPEG and WebP validation checks supported static containers and headers, not complete entropy decoding.
55
+
56
+ Image output requires an exact `path`; there is no output-directory setting, generated name, or extension adjustment. The captured session cwd and raw input are passed to Pi's public `createWriteTool` with custom binary filesystem operations. Pi owns path normalization and the absolute-path mutation queue. This keeps relative/absolute paths, tilde, leading `@`, file URLs, Unicode-space normalization, dot segments, and literal shell syntax aligned with `write` without importing private utilities.
57
+
58
+ Preflight uses the same public factory with non-writing operations. It creates parent directories and checks existing targets or missing targets' actual parents without truncating files. Existing writable targets do not require a writable parent directory. File and directory symlinks are followed, including final dangling symlinks when their target parent permits creation. Only the entered prompt and fixed image options reach the HTTP client; local paths are not sent to the endpoint.
59
+
60
+ The binary writer preserves validated image bytes and normal Node write/truncate/umask behavior, including overwrites and symlink following. It passes cancellation to the byte write and drains that operation before releasing the queue. Partial writes are not deleted or rolled back. Pi's in-process queue uses the real path for existing destinations and falls back to the resolved path when a destination is missing or has a non-directory component. Existing symlink aliases therefore share a queue; missing/dangling aliases and separate processes do not have that guarantee. Paths and preflight are not a filesystem sandbox.
61
+
62
+ Settings remain separate ordered, same-directory temporary-file-plus-rename transactions with rollback; image writes do not use that settings policy.
63
+
64
+ The extension has no mutable leading prompt, context hook, or deferred tool loader. Explicit tool toggles are loadout transitions; later ordinary requests preserve their established prefix. Manual generation appends one result message without triggering inference. Immutable artifact metadata stays in tool details or the result message; it does not cause automatic regeneration after reload, branching, or compaction.
@@ -0,0 +1,65 @@
1
+ # Verification and release handoff
2
+
3
+ Deterministic tests validate the TypeScript implementation, not the availability of the internal Codex endpoint for a real account. No live image request is part of the default tests, build, package load, or Status action.
4
+
5
+ ## Deterministic coverage
6
+
7
+ Package tests cover synthetic OAuth metadata/resolution, golden HTTP payloads, fixed destination and header filtering, redaction, redirects, quota/status errors, deadlines, bounded/chunked streams, socket cancellation, image validation, path preflight, native-style binary writes, settings transactions, UI, and lifecycle cleanup.
8
+
9
+ Real Pi SDK fixtures exercise hidden-tool behavior through direct activation, codemode, tool search, and nested execution; enabled generation; normalized model-visible prefixes and toggle transitions; command modes; direct SDK disposal; and the package entrypoint through Pi's Jiti loader. All credentials, model streams, and image responses in those tests are synthetic.
10
+
11
+ Regression coverage includes required exact paths, native `write` path equivalence, overwrites, symlink and permission branches, partial write behavior, destination input cancellation, release-then-click mouse dispatch without a render boundary, save failures after normal Settings closure, partial tool-application rollback, bounded filesystem error text, terminal-marker injection, and transport results returned after SDK invalidation.
12
+
13
+ Run the repository gates from its root:
14
+
15
+ ```bash
16
+ npm run check
17
+ npm test
18
+ npm run package:pack -- codex-imagegen
19
+ ```
20
+
21
+ Build Kit before consumer tests and do not overlap root checks with Kit builds. Inspect a real tarball in a temporary directory as well as the pack dry-run list. Do not publish it as a smoke test.
22
+
23
+ For loading, use a controlled non-interactive subprocess with a temporary Pi agent directory and no credentials:
24
+
25
+ ```bash
26
+ pi --mode rpc --no-extensions -e ./packages/pi-codex-imagegen
27
+ ```
28
+
29
+ The harness must establish RPC readiness, check `/codex-imagegen` rejection, reload settings, and shut down cleanly. It must not send an ordinary model prompt or attempt generation. The source package has no required generated runtime build.
30
+
31
+ ## Account-owner setup
32
+
33
+ Responsible role: account owner. Prerequisite: an account allowed to use Codex images and the supported Pi `openai-codex` provider. Sign in using Pi's `/login` if this provider is not configured. Confirm only the non-secret Status output; never paste credentials into chat or an issue. Codex CLI-only login is not automatically reused.
34
+
35
+ Expected result: Pi owns credential storage and refresh. The extension creates no credential file or migration. Actual image access remains unverified until the live procedure succeeds.
36
+
37
+ ## Live-provider smoke
38
+
39
+ Responsible role: maintainer/account owner. Prerequisites: explicit permission to consume quota, compatible OAuth, network access, and completion of deterministic checks. This procedure is not authorization to spend quota.
40
+
41
+ 1. Load only this extension in a temporary or controlled Pi configuration. Keep `toolEnabled` false initially.
42
+ 2. Open `/codex-imagegen` and inspect Status without causing auth refresh or an image request.
43
+ 3. Choose Generate Image, enter one simple prompt, then provide an explicit path in a disposable directory. Existing files and symlink targets can be overwritten. Submit once; do not retry automatically.
44
+ 4. Confirm that a supported image exists at that exact path, inspect its actual bytes/dimensions, and confirm that the reported absolute path is correct. An extension does not request format conversion.
45
+ 5. With separate authorization for another image, request a transparent background and inspect actual alpha. A checkbox or successful HTTP response is not proof of transparency.
46
+ 6. If tool use is to be claimed as live-verified, enable it explicitly and authorize one additional model invocation; confirm saved-path and image results, then restore the desired setting.
47
+ 7. Record only sanitized outcome, media/dimensions, and a non-secret request ID if useful. Do not retain tokens, account identifiers, prompts containing secrets, or raw upstream error bodies.
48
+
49
+ Stop after one clear entitlement, unsupported-endpoint, or external failure. Record it and return to deterministic tests; do not change identity headers, bypass policy, or switch credentials/models to make the smoke pass.
50
+
51
+ Remote generation cancellation and quota refunds are not guaranteed even after a successful smoke. Local cancellation should close the owned request and prevent stale result publication. A filesystem write already started can leave complete or partial bytes; cancellation does not restore previous content.
52
+
53
+ ## Physical-terminal review
54
+
55
+ Responsible role: terminal user. Prerequisites: the built Kit dependency, intended terminal/input mode, and synthetic prompts for editor checks. Review menu navigation, the required destination input and overwrite/symlink warning, remapped cancellation, hard Ctrl+C, IME, Backspace/newlines, large and multiline paste, mouse press/release/click, narrow/short terminal layouts, theme changes, and resizing.
56
+
57
+ Review inline preview with the intended image protocol only after a live image has been separately authorized or with an existing safe fixture. Confirm a readable file path when inline rendering is disabled or unavailable. The external-editor shortcut is intentionally unavailable in this owned prompt dialog.
58
+
59
+ Expected result: Pi-native input behavior and bounded screens. Mocked frames do not prove physical terminal behavior. Keep untested terminal/input modes listed as unverified rather than claim general visual compatibility.
60
+
61
+ ## Current external limits and release restriction
62
+
63
+ Live account/endpoint compatibility, actual generated image bytes, transparent alpha, live tool use, physical terminal/IME behavior, and runtime-specific proxy setups remain unverified. The tests must not be described as proving those paths.
64
+
65
+ Keep the feature experimental. Do not publish the initial package until the supported live generation path is verified and publication is explicitly approved. Do not create version tags, change npm visibility, or dispatch release workflows as part of implementation verification.
@@ -0,0 +1,65 @@
1
+ # Workflows
2
+
3
+ The manual menu and the optional model tool use the same image generation pipeline. These diagrams describe the current implementation. See [Architecture](./architecture.md) for component and data boundaries, including the experimental endpoint warning.
4
+
5
+ ## Manual and model-driven generation
6
+
7
+ Manual generation does not require tool enablement. Model-driven generation requires explicit opt-in through Settings. Both routes require a prompt and an exact destination path.
8
+
9
+ ```mermaid
10
+ flowchart TD
11
+ Start["Generate an image"] --> Caller{"Who starts generation?"}
12
+ Caller -->|User| Menu["Open /codex-imagegen"]
13
+ Menu --> Action["Select Generate Image"]
14
+ Action --> Input["Enter prompt and destination path"]
15
+ Caller -->|Pi agent| Enabled{"Is toolEnabled true?"}
16
+ Enabled -->|No| Unavailable["Tool unavailable<br/>Default state"]
17
+ Enabled -->|Yes| Tool["Call codex_imagegen<br/>prompt, path, optional<br/>transparentBackground"]
18
+ Input --> Pipeline["Shared generation pipeline"]
19
+ Tool --> Pipeline
20
+ Pipeline --> Saved["Save image"]
21
+ Saved --> Route{"Which route started it?"}
22
+ Route -->|Manual| Message["Append result at conversation tail<br/>Do not start a model turn"]
23
+ Route -->|Tool| Result["Return tool result<br/>Image, absolute path, and metadata"]
24
+ ```
25
+
26
+ The command requires TUI mode and accepts no arguments. The enabled tool also works in headless modes. Manual preview resizing does not change the original image file.
27
+
28
+ ## Request sequence
29
+
30
+ The extension checks the destination before making the HTTP request. After each asynchronous step, it checks whether the session and request still own the operation before continuing.
31
+
32
+ ```mermaid
33
+ sequenceDiagram
34
+ participant Caller as Menu or tool
35
+ participant Extension as Extension
36
+ participant Files as Filesystem
37
+ participant Pi as Pi ModelRegistry
38
+ participant API as ChatGPT endpoint
39
+
40
+ Caller->>Extension: Prompt, path, background option
41
+ Extension->>Extension: Check session, input, and busy state
42
+ Extension->>Files: Preflight path; create parent directories if needed
43
+ Extension->>Pi: getProviderAuth("openai-codex")
44
+ Pi-->>Extension: Resolved OAuth authentication
45
+ Extension->>Extension: Recheck session and authentication compatibility
46
+ Extension->>API: POST /backend-api/codex/images/generations
47
+ alt Successful response with a valid image
48
+ API-->>Extension: JSON containing one Base64 image
49
+ Extension->>Extension: Validate format, byte size, and dimensions
50
+ Extension->>Files: Write original image bytes
51
+ Extension-->>Caller: Image, absolute path, and metadata
52
+ else Request failure or invalid image
53
+ Extension-->>Caller: Report error; no automatic retry
54
+ end
55
+ ```
56
+
57
+ The model is fixed to `gpt-image-2`, with size and quality set to `auto`. The extension does not generate filenames, adjust extensions, or convert image formats. Authentication waits are limited to 30 seconds within a five-minute total authentication/HTTP budget.
58
+
59
+ Preflight can create parent directories even if generation later fails. A filesystem write failure can leave a truncated or partially replaced file; image writes are not atomic and are not rolled back.
60
+
61
+ ## Implementation references
62
+
63
+ [`codex-imagegen.ts`](../src/codex-imagegen.ts) owns the shared generation pipeline and result publication. [`menu.ts`](../src/menu.ts) owns manual generation, and [`image-client.ts`](../src/image-client.ts) owns HTTP requests and authentication checks.
64
+
65
+ See the [protocol contract](./protocol.md) for detailed failure and cancellation behavior, and the [verification guide](./verification.md) for remaining live checks.
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@narumitw/pi-codex-imagegen",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Experimental Pi image generation through the Codex image endpoint, without a Codex agent.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "private": false,
8
+ "keywords": [
9
+ "pi-package",
10
+ "pi-extension",
11
+ "pi",
12
+ "codex",
13
+ "image-generation",
14
+ "chatgpt"
15
+ ],
16
+ "files": [
17
+ "src",
18
+ "docs",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "pi": {
23
+ "extensions": [
24
+ "./src/index.ts"
25
+ ]
26
+ },
27
+ "scripts": {
28
+ "check": "biome check . && npm run typecheck",
29
+ "format": "biome check --write .",
30
+ "typecheck": "tsc --noEmit"
31
+ },
32
+ "dependencies": {
33
+ "@narumitw/pi-tui-kit": "^0.66.0"
34
+ },
35
+ "peerDependencies": {
36
+ "@earendil-works/pi-coding-agent": "*",
37
+ "@earendil-works/pi-tui": "*",
38
+ "typebox": "*"
39
+ },
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "https://github.com/narumiruna/pi-extensions",
43
+ "directory": "packages/pi-codex-imagegen"
44
+ }
45
+ }