@code-yeongyu/senpi 2026.10.25-3 → 2026.10.25-4

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.
Files changed (76) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/bundle/chunks/{chunk-WLHNEUGD.js → chunk-2RB5EL4X.js} +1 -1
  3. package/dist/bundle/chunks/{chunk-MJ5NNWX4.js → chunk-3QCYBOKN.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-FFQOEC76.js → chunk-4MOZXOJX.js} +3 -3
  5. package/dist/bundle/chunks/{chunk-ODTGC6YU.js → chunk-5JJDR6XI.js} +1 -1
  6. package/dist/bundle/chunks/chunk-6VWIMHMH.js +2 -0
  7. package/dist/bundle/chunks/{chunk-SWJXRC2I.js → chunk-BZ7726QO.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-YRF4I43T.js → chunk-C2MQ4QXN.js} +12 -12
  9. package/dist/bundle/chunks/{chunk-7W7OJDIY.js → chunk-DODH3N6U.js} +4 -4
  10. package/dist/bundle/chunks/{chunk-EHQXLHRB.js → chunk-E6D4RIT7.js} +2 -2
  11. package/dist/bundle/chunks/{chunk-6O4SEW2W.js → chunk-J37GRED2.js} +1 -1
  12. package/dist/bundle/chunks/chunk-JMOUU75H.js +2 -0
  13. package/dist/bundle/chunks/{chunk-Z3UYNSVR.js → chunk-KKD4CYCI.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-JA2R2ZSE.js → chunk-KNVNKDER.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-CNL6QSUB.js → chunk-LOIF6PHI.js} +2 -2
  16. package/dist/bundle/chunks/{chunk-P3M2PF6K.js → chunk-N7IN46Q5.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-C5UFJ7B3.js → chunk-PT6JJUN2.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-O3Q2ET6W.js → chunk-SBGIXMX3.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-HVJI5T75.js → chunk-STMXIBXF.js} +2 -2
  20. package/dist/bundle/chunks/{chunk-H3HNMY2W.js → chunk-TBU6VYHN.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-UQNRW3VU.js → chunk-V2UYXTRR.js} +1 -1
  22. package/dist/bundle/chunks/chunk-XMJKZK5H.js +2 -0
  23. package/dist/bundle/chunks/cli-main-YYH3IBC6.js +3 -0
  24. package/dist/bundle/chunks/{dispatch-NYAULNVW.js → dispatch-MXG5YWLV.js} +1 -1
  25. package/dist/bundle/chunks/{host-command-Z3WPHJOW.js → host-command-TDLLHXVI.js} +1 -1
  26. package/dist/bundle/chunks/{host-lifecycle-ONQIMWMX.js → host-lifecycle-3VHHIGDL.js} +1 -1
  27. package/dist/bundle/chunks/host-lifecycle.js +1 -1
  28. package/dist/bundle/chunks/{host-session-command-J65ENSV5.js → host-session-command-56XF6ACS.js} +1 -1
  29. package/dist/bundle/chunks/{host-socket-request-3CWE4265.js → host-socket-request-QL2WEZTN.js} +1 -1
  30. package/dist/bundle/chunks/interactive-mode-OEPULLZK.js +2 -0
  31. package/dist/bundle/chunks/{multi-session-host-YI2WZOET.js → multi-session-host-Z2CW4SDM.js} +2 -2
  32. package/dist/bundle/chunks/{package-manager-cli-GHZPJMRF.js → package-manager-cli-N55U6PEO.js} +1 -1
  33. package/dist/bundle/chunks/rotation-stream-CBGCBYHV.js +2 -0
  34. package/dist/bundle/chunks/rpc-mode-ETXQWEB2.js +2 -0
  35. package/dist/bundle/chunks/{rpc-monitor-source-FFEQS744.js → rpc-monitor-source-AE3C6EQV.js} +1 -1
  36. package/dist/bundle/chunks/{schedule-command-YWG6D6ZF.js → schedule-command-VS7CZC2J.js} +1 -1
  37. package/dist/bundle/chunks/session-control-endpoint-4LEIDIVI.js +3 -0
  38. package/dist/bundle/chunks/session-picker-E4KUJDLO.js +2 -0
  39. package/dist/bundle/chunks/session-worker.js +45 -45
  40. package/dist/bundle/cli.js +2 -2
  41. package/dist/bundle/host-supervisor.js +1 -1
  42. package/dist/bundle/index.js +1 -1
  43. package/dist/bundle/rpc-entry.js +1 -1
  44. package/dist/bundle/runtime-manifest.json +1 -1
  45. package/dist/core/extensions/builtin/mcp/elicitation.js +2 -4
  46. package/dist/core/session-control-actions.js +0 -2
  47. package/dist/modes/interactive/session-control-attach.d.ts +20 -0
  48. package/dist/modes/interactive/session-control-attach.js +13 -0
  49. package/dist/modes/interactive/session-control-commands.js +16 -6
  50. package/dist/modes/interactive/session-control-registry.d.ts +2 -1
  51. package/dist/modes/interactive/session-control-registry.js +3 -2
  52. package/dist/modes/interactive/session-control-rpc-commands.d.ts +4 -2
  53. package/dist/modes/interactive/session-control-rpc-commands.js +114 -4
  54. package/dist/modes/interactive/session-control-server.js +9 -3
  55. package/dist/modes/rpc/connection-handler.js +6 -40
  56. package/dist/modes/rpc/custom-capability.d.ts +6 -0
  57. package/dist/modes/rpc/custom-capability.js +6 -0
  58. package/dist/modes/rpc/get-entries-command.d.ts +13 -0
  59. package/dist/modes/rpc/get-entries-command.js +61 -0
  60. package/dist/modes/rpc/get-entries-page.d.ts +22 -0
  61. package/dist/modes/rpc/get-entries-page.js +41 -2
  62. package/dist/modes/rpc/host-capabilities.js +4 -1
  63. package/dist/modes/rpc/host-observe-request.d.ts +2 -1
  64. package/dist/modes/rpc/host-observe-request.js +4 -1
  65. package/dist/modes/rpc/rpc-read-response-types.d.ts +2 -0
  66. package/dist/modes/rpc/rpc-session-command-types.d.ts +8 -1
  67. package/docs/rpc.md +43 -11
  68. package/package.json +6 -6
  69. package/dist/bundle/chunks/chunk-3LNSLJ7N.js +0 -2
  70. package/dist/bundle/chunks/chunk-MSQCTH6V.js +0 -2
  71. package/dist/bundle/chunks/cli-main-HEKFFB5S.js +0 -3
  72. package/dist/bundle/chunks/interactive-mode-DEPQC6TX.js +0 -2
  73. package/dist/bundle/chunks/rotation-stream-ZPVCFOVD.js +0 -2
  74. package/dist/bundle/chunks/rpc-mode-ORHBGBBV.js +0 -2
  75. package/dist/bundle/chunks/session-control-endpoint-36HAQSQO.js +0 -3
  76. package/dist/bundle/chunks/session-picker-25H5KNYP.js +0 -2
package/docs/rpc.md CHANGED
@@ -1957,13 +1957,17 @@ Environment overrides beat the file, and invalid values fall through to the next
1957
1957
 
1958
1958
  The host exits only after the window elapses with NO attached client connections and NO active turns — continuously.
1959
1959
  Any attached connection or agent turn resets the window, so a busy host never exits. A connection attaches with its
1960
- first request line, unless that line is an OBSERVING read: `get_protocol_info` or `list_sessions` carrying
1961
- `"observe": true`, or a `warm` (marked or not - see "Warming a host"). A connection that only ever sends observing reads never counts and never resets the window, so a
1960
+ first request line, unless that line is an OBSERVING read: a side-effect-free read carrying `"observe": true` -
1961
+ `get_protocol_info`, `list_sessions`, `subscribe_sessions`, `unsubscribe_sessions`, `get_effect_status`,
1962
+ `get_pending_inputs`, `get_subscription_limits`, and the session reads `get_state` and `get_entries` (capability
1963
+ `observe_reads`) - or a `warm` (marked or not - see "Warming a host"). A connection that only ever sends observing reads never counts and never resets the window, so a
1962
1964
  poller (`senpi host status [--all]`, which marks both of its reads, a doctor loop, a runtime panel) can look at every
1963
1965
  endpoint as often as it likes without keeping any of them alive; the first request that is anything else attaches the
1964
1966
  connection from then on, and `observe` on any other command is ignored. While a connection has not sent its first
1965
1967
  line yet the host does not exit, and the window keeps running. Hosts that predate the field ignore it, so a marked read
1966
- works against every generation.
1968
+ works against every generation. A watcher can therefore read a session's state and history (`get_state`,
1969
+ `get_entries` with `observe: true`) as often as it likes: the host's attached count stays at 0 and its idle window
1970
+ keeps running.
1967
1971
 
1968
1972
  A connection from one of the host's OWN sessions is DEPENDENT and never counts either. A host exports its generation
1969
1973
  id (`SENPI_RPC_HOST_INSTANCE_ID`) to the sessions it runs, and `RpcClient` sends that id as `"origin_host_instance"`
@@ -2170,8 +2174,10 @@ one with `pi.session.registerControlEndpoint({ inboxDir, drain, isSessionReferen
2170
2174
  [pi.session](extensions.md#pisession)). OmO's thread component registers one at startup; a plain `senpi` with no
2171
2175
  registrant opens no socket and writes no registry directory.
2172
2176
 
2173
- - **Platform.** POSIX terminals only. On win32 the registration answers
2174
- `{ status: "unsupported", reason: "unsupported_platform" }` and registers nothing. On a multi-session host the
2177
+ - **Platform.** Every platform. On win32 the socket path below is the endpoint's logical address: the secret is
2178
+ written beside it, and the listener binds the named pipe the host transport derives from the path and the secret
2179
+ (`\\.\pipe\senpi-rpc-<32hex>`), the address every client already connects to after reading the secret. It is
2180
+ registered and listed like a POSIX terminal. On a multi-session host the
2175
2181
  same call binds nothing - the host's public socket is the endpoint - see "Waking a host session (`wake`)".
2176
2182
  - **Socket and auth.** The endpoint listens on `<agentDir>/rpc/tui/t-<16hex>.sock` (16 hex of the SHA-256 of a
2177
2183
  fresh instance id). When that path is longer than a Unix socket path allows, it moves to
@@ -2192,13 +2198,16 @@ registrant opens no socket and writes no registry directory.
2192
2198
  - **Commands.** Anything not listed below is answered `unsupported` as data. No command opens another session or
2193
2199
  runs a command; input goes through the terminal's admission (`steer`/`follow_up`/`prompt` below), so the
2194
2200
  user's draft still holds it.
2195
- - `get_protocol_info`: `mode: "tui"`, `endpoint_kind: "tui"`, `capabilities: ["tui_control", "session_status"]`, `generation: 0`, the endpoint's
2201
+ - `get_protocol_info`: `mode: "tui"`, `endpoint_kind: "tui"`, `capabilities: ["tui_control", "session_status",
2202
+ "tui_observer", "observe_reads", "entries_tail"]` (`tui_observer`: the observe-and-drive set below), `generation: 0`, the endpoint's
2196
2203
  `instanceId`, and `commands`: every command this endpoint accepts. A terminal from before the session
2197
2204
  controls below lists no `commands`.
2198
2205
  - `list_sessions`: exactly one row, `kind: "interactive"`, `surface: "tui"`, `attachments: 1`.
2199
2206
  - `get_state`: the RPC session state plus `turn_epoch`, `blocking_question`, `compacting`,
2200
2207
  `editor_has_draft` and `state_version`.
2201
2208
  - `get_messages`.
2209
+ - `get_entries { since?, before?, limit?, tail?, maxBytes? }`: the host's answer, pages and tail pages included
2210
+ (see `get_entries`).
2202
2211
  - `set_session_name { name }`: a blank name is refused.
2203
2212
  - `subscribe { cursor? }`: a feed of `session_control_event { seq, kind, data }` records, where `kind` is
2204
2213
  `state`, `report` (an assistant message's text), `question` (pending question ids) or `completion` (the
@@ -2220,10 +2229,25 @@ registrant opens no socket and writes no registry directory.
2220
2229
  `queued`; `held_draft` (the user is composing) and `turn_conflict` are refusals with a reason and an action.
2221
2230
  Unlike a host's input, the message lands as a remote delivery (a `session_control_delivery` entry the
2222
2231
  terminal renders as "remote message"), not a user message: there are no prompt templates, slash commands or
2223
- skills, no admission receipt, and a repeated `clientMessageId` answers `duplicate: true`. Frames carrying
2232
+ skills. Input sent with a `clientMessageId` is answered with an admission receipt,
2233
+ `admission { clientMessageId, durableSessionId, disposition }`; a retry with the same id and the same input is
2234
+ answered from it, with `replayed: true` (and `duplicate: true`) and the original `disposition`, and delivers
2235
+ nothing; the same id with different input is refused `client_message_id_conflict`. Frames carrying
2224
2236
  `images`, `thinkingLevel`, `expandPromptTemplates`, `unknownCommandAsText`, `sessionTitlePrompt` or
2225
2237
  `enqueueOrder` are refused `unsupported_field`, naming them.
2226
2238
  - `get_effect_status { effectId, sessionPath? }`: the same effect ledger as a host.
2239
+ - `set_client_info { width, capabilities? }`: declares the connection's roles (`interactive_user`,
2240
+ `task_parent`), fixed once declared (`connection_role_fixed`), as on a host.
2241
+ - `attach_session { sessionId, durableSessionId, expectedHostInstance? }`: a live attachment, as on a host:
2242
+ `sessionId` is the terminal's session id from `list_sessions`, `durableSessionId` the same id, and
2243
+ `expectedHostInstance`, when sent, this endpoint's `instanceId`. Answers `{ sessionId, attached: true }` after the
2244
+ replay of the in-flight snapshot, then the session's records follow; another session is `unknown_session`, an
2245
+ identity that does not match is `session_identity_mismatch`.
2246
+ - `release_attachment { sessionId }`: drops this connection's attachment, answered `{ deferred: false }`;
2247
+ `session_not_attached` when it holds none.
2248
+ - `abort { intent?, effectId?, awaitIdle?, clearQueue?, graceMs? }`: the host's `abort` and effect receipts.
2249
+ `intent: "stop"` is refused `stop_requires_interactive_client: declare interactive_user with set_client_info first`
2250
+ until the connection declared `interactive_user`.
2227
2251
  - `wake { delivery_ids? }`: one drain pass, answered `{ admitted: [{ delivery_id, kind }] }`.
2228
2252
  - `extension_ui_response`: answers only a question this session asked and still waits on
2229
2253
  (`unknown_request` / `question_incomplete` / `invalid_response` otherwise). `uiRequestId` names the
@@ -2246,7 +2270,6 @@ registrant opens no socket and writes no registry directory.
2246
2270
  settles before the answer. Answers `{ interrupted: true, turnId }` with the `turn_epoch` it stopped. An idle
2247
2271
  session answers `{ interrupted: false }`; a `turnId` that is not the running turn answers
2248
2272
  `{ interrupted: false, turnId }` with the running one and leaves it alone. The session stays open.
2249
- - `prompt`, `steer` and `follow_up` are `unsupported`.
2250
2273
  - **Admission.** A message from another session enters only through the registrant's drain, which calls
2251
2274
  `pi.session.admitExternalMessage({ delivery_id, text, deliverAs, expected_turn_id? })`. One synchronous call
2252
2275
  decides and acts:
@@ -4457,6 +4480,15 @@ Response:
4457
4480
 
4458
4481
  An unpaged request (neither bound) answers exactly as before while the whole history fits in 48 MiB. A longer history is refused with `errorCode: "response_too_large"` instead of an answer that would close the connection; read it in pages.
4459
4482
 
4483
+ **Tail pages** (capability `entries_tail`). Pass `tail` (a positive integer) to read the NEWEST entries first: the answer holds the newest `tail` entries of the range, in append order, under the same `maxBytes` rule (8 MiB when only `tail` is given, capped at 48 MiB), and always at least the newest one. While older entries remain it carries `hasMore: true` and `next_before`, the id of the oldest entry it returned; ask again with `before: next_before` to walk back until `hasMore` is `false`. `before` (an entry id) limits any read to entries strictly before it; an id that names no entry is refused with `errorCode: "not_found"`. `since` is unchanged, and `since` and `before` may bound one range together. `tail` and `limit` cannot be combined (`invalid_argument`): `limit` pages forward from the range's start, `tail` backward from its end.
4484
+
4485
+ ```json
4486
+ {"type": "get_entries", "tail": 200, "observe": true}
4487
+ {"type": "get_entries", "tail": 200, "before": "<next_before>", "observe": true}
4488
+ ```
4489
+
4490
+ `get_entries` and `get_state` may carry `observe: true`: on a host such a read never counts as an attachment (see the idle-exit window).
4491
+
4460
4492
  A single entry larger than 48 MiB cannot travel in any answer, so a read whose next entry is that large (paged or not) is refused with `response_too_large` naming the entry. While a walk has more pages, the host keeps the session's full history in memory for the next page; it lets it go 30 s after the last page request, so a client that stops mid-walk does not pin the history.
4461
4493
 
4462
4494
  #### get_tree
@@ -5500,9 +5532,9 @@ reconnect for this purpose because their capability metadata is per request.
5500
5532
 
5501
5533
  Legacy elicitation has no reliable parent tool-call identifier in the received SDK
5502
5534
  handler metadata. With multiple `tools/call` operations in flight on one physical
5503
- legacy client, enforced elicitation fails closed with JSON-RPC `-32603` and
5504
- `data.reason: "ambiguous_legacy_origin"`. The error explains that concurrent legacy
5505
- calls make the origin ambiguous and recommends sequential calls or an MRTR server.
5535
+ legacy client, enforced elicitation fails closed with the same fixed JSON-RPC
5536
+ processing error as an unavailable presenter: code `-32603`, message
5537
+ `Elicitation processing unavailable`, and no `data`.
5506
5538
  No form is displayed and no human answer is admitted. Without enforcement, legacy
5507
5539
  clients keep the SDK request method, origin handling, and concurrent-call behavior.
5508
5540
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@code-yeongyu/senpi",
3
- "version": "2026.10.25-3",
3
+ "version": "2026.10.25-4",
4
4
  "description": "Coding agent CLI with read, bash, edit, write tools and session management",
5
5
  "type": "module",
6
6
  "piConfig": {
@@ -71,9 +71,9 @@
71
71
  },
72
72
  "dependencies": {
73
73
  "@earendil-works/chord": "0.99.1",
74
- "@earendil-works/pi-agent-core": "npm:@code-yeongyu/senpi-agent-core@2026.10.25-3",
75
- "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.10.25-3",
76
- "@earendil-works/pi-tui": "npm:@code-yeongyu/senpi-tui@2026.10.25-3",
74
+ "@earendil-works/pi-agent-core": "npm:@code-yeongyu/senpi-agent-core@2026.10.25-4",
75
+ "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.10.25-4",
76
+ "@earendil-works/pi-tui": "npm:@code-yeongyu/senpi-tui@2026.10.25-4",
77
77
  "@silvia-odwyer/photon-node": "0.3.4",
78
78
  "chalk": "6.0.0",
79
79
  "cross-spawn": "7.0.6",
@@ -92,8 +92,8 @@
92
92
  "yaml": "2.9.1",
93
93
  "@anthropic-ai/claude-agent-sdk": "0.3.306",
94
94
  "@anthropic-ai/sdk": "0.127.0",
95
- "@code-yeongyu/senpi-codemode": "2026.10.25-3",
96
- "@earendil-works/pi-pty": "npm:@code-yeongyu/senpi-pty@2026.10.25-3",
95
+ "@code-yeongyu/senpi-codemode": "2026.10.25-4",
96
+ "@earendil-works/pi-pty": "npm:@code-yeongyu/senpi-pty@2026.10.25-4",
97
97
  "@modelcontextprotocol/sdk": "1.32.1",
98
98
  "@mozilla/readability": "0.6.0",
99
99
  "linkedom": "0.18.13",
@@ -1,2 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{rateLimitModelFamily,usageLimitResetMs}from"./chunk-MSQCTH6V.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{rememberResolvedReferenceValue}from"./chunk-DLAY7CIU.js";import{normalizeProviderError}from"./chunk-TAV6QZFM.js";import{extract429RetryAfterMs}from"./chunk-PELNNWGO.js";import{getShellConfig}from"./chunk-BWA4FVFW.js";import{Compile,getOverflowPatterns}from"./chunk-E6WYH3ZL.js";import{ConfigReferenceError,PROVIDER_NOT_CONFIGURED_PREFIX,USAGE_LIMIT_EXHAUSTION,isOAuthRefreshUnavailableError,listSlots}from"./chunk-6AOVUTUR.js";import{typebox_exports}from"./chunk-MIENF2YK.js";function rendezvousOrder(key,slots,hasher){return[...slots].map(slot=>({slot,score:hasher(`${key}\0${slot.name}`)})).sort((left,right)=>right.score>left.score?1:right.score<left.score?-1:0).map(({slot})=>slot)}function applyAccountOrder(order,ranked){if(order===void 0||order.length===0)return[...ranked];let byName=new Map(ranked.map(slot=>[slot.name,slot])),front=[];for(let name of order){let slot=byName.get(name);slot!==void 0&&!front.includes(slot)&&front.push(slot)}return[...front,...ranked.filter(slot=>!front.includes(slot))]}function withoutOrderedAccount(credential,name){if(credential.order===void 0||!credential.order.includes(name))return credential;let order=credential.order.filter(entry=>entry!==name),next={...credential};return order.length===0?delete next.order:next.order=order,next}var PRE_COMMIT_EVENT_TYPES=new Set(["start","text_start","thinking_start","toolcall_start"]);function isCommittedRotationOutput(event){return!PRE_COMMIT_EVENT_TYPES.has(event.type)}function isRotationStreamStart(event){return event.type==="start"}function rotationErrorFromEvent(event){if(event.type!=="error")return;let failure=new Error(event.error.errorMessage??"provider stream error"),status=event.error.providerDiagnostic?.httpStatus;return status===void 0?failure:Object.assign(failure,{status})}var DEFAULT_SLOT_BLOCK_MS=6e4,MAX_SLOT_BLOCK_MS=2880*60*1e3;function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ACCOUNT_USAGE_LIMIT_TEXT=new RegExp([...USAGE_LIMIT_EXHAUSTION.markers.map(escapeRegExp),String.raw`\b(?:hit|reached)\s+your\b[^.]*?\blimit\b`,String.raw`\busage\s+limit\s+reached\b`,String.raw`\b(?:Go|Free)UsageLimitError\b`,String.raw`\bblocking_limit\b`,String.raw`\brapid_refill_breaker\b`,String.raw`\bquota\s+exceeded\b`].join("|"),"i");function isAccountUsageLimitText(text){return ACCOUNT_USAGE_LIMIT_TEXT.test(text)}var COOLDOWN_BASE_MS=DEFAULT_SLOT_BLOCK_MS,COOLDOWN_CAP_MS=MAX_SLOT_BLOCK_MS,RETRY_SAME_MAX_ATTEMPTS=2,ACCOUNT_POOL_REFUSAL_NOTE="No request was sent: the account pool refused it locally.";function rateLimitCooldown(failureCount,serverHintMs,policy={}){let cap=policy.capMs??COOLDOWN_CAP_MS,base=policy.baseMs??COOLDOWN_BASE_MS,backoff=Math.min(cap,base*2**Math.max(0,failureCount)),floored=serverHintMs===void 0?backoff:Math.max(backoff,serverHintMs);return{cooldownMs:Math.min(cap,floored),retryAfterWasCapped:floored>cap}}function usageLimitCooldown(resetMs,policy={}){let cap=policy.capMs??COOLDOWN_CAP_MS;return{cooldownMs:Math.min(cap,resetMs),retryAfterWasCapped:resetMs>cap}}var INVALID_KEY_TEXT=/invalid[ _-]?(?:api[ _-]?)?key|authentication[_ ]?error|invalid x-api-key|unauthorized/i,ACCOUNT_SCOPED_403_TEXT=/account|credential|token|api[ _-]?key|organization|subscription/i,RATE_LIMIT_TEXT=/rate[ _-]?limit|too many requests|resource_exhausted/i,BILLING_TEXT=/billing|credits?[ _-]?(?:required|exhausted|balance)|insufficient[ _-]?(?:funds|quota|credit)|payment[ _-]?required|quota[ _-]?exhausted/i,OVERLOAD_TEXT=/overloaded/i,NETWORK_TEXT=/econnreset|econnrefused|etimedout|enotfound|socket hang up|fetch failed|network error|request timed out/i,WEBSOCKET_REQUEST_FAULT_TEXT=/websocket closed 100[89]\b/i,WEBSOCKET_TRANSPORT_FAULT_TEXT=/websocket (?:closed|error|connect timeout|liveness timeout)/i,FAIL_FAST_TEXT=/context[ _-]?(?:length|window)|maximum context|invalid[ _-]?model|model[ _-]?not[ _-]?found|malformed[ _-]?stream|premature[ _-]?(?:close|stream)/i,ABORT_TEXT=/\baborted?\b/i,TEMPORARY_FAULT_TEXT=/time[ds]?[ _-]?out|timed out|disconnect|reset before|connection reset|gateway|temporarily|unavailable/i;function isAbort(error,message){return error instanceof Error&&error.name==="AbortError"?!0:ABORT_TEXT.test(message)}function isOverflowText(text){return getOverflowPatterns().some(pattern=>pattern.test(text))}function classifyCredentialFailure(error,context={}){if(isOAuthRefreshUnavailableError(error))return{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS};let normalized=normalizeProviderError(error),text=normalized.messageCarriesBody?normalized.message:`${normalized.message} ${normalized.body??""}`,status=normalized.status,failureCount=context.failureCount??0;if(isAbort(error,text))return{kind:"fail_request"};if(text.includes(ACCOUNT_POOL_REFUSAL_NOTE))return{kind:"fail_request"};let providerFault=status===408||status!==void 0&&status>=500&&status<600||status===void 0&&(TEMPORARY_FAULT_TEXT.test(text)||NETWORK_TEXT.test(text)||OVERLOAD_TEXT.test(text)),usageLimit=isAccountUsageLimitText(text)&&!isOverflowText(text),limitText=RATE_LIMIT_TEXT.test(text)||usageLimit;if(text.includes(PROVIDER_NOT_CONFIGURED_PREFIX))return{kind:"failover",block:{reason:"auth_error"}};if(status===401||!providerFault&&status!==429&&INVALID_KEY_TEXT.test(text))return{kind:"failover",block:{reason:"auth_error"}};if(status===403&&!limitText)return ACCOUNT_SCOPED_403_TEXT.test(text)?{kind:"failover",block:{reason:"auth_error"}}:{kind:"fail_request"};if(status===402||!providerFault&&BILLING_TEXT.test(text))return{kind:"failover",block:{reason:"account_disabled"}};if(status===429||limitText){let nowMs=context.nowMs??Date.now(),hint=extract429RetryAfterMs({status:status??429,bodyText:text},nowMs)??(usageLimit?normalized.retryAfterMs??usageLimitResetMs(text,nowMs):void 0),modelFamily=rateLimitModelFamily(text),policy={baseMs:context.cooldownBaseMs,capMs:context.cooldownCapMs};return{kind:"failover",block:{reason:"rate_limit",...usageLimit&&hint!==void 0&&hint>0?usageLimitCooldown(hint,policy):rateLimitCooldown(failureCount,hint,policy),...modelFamily===void 0?{}:{modelFamily}}}}return isOverflowText(text)||status===400||status===404||FAIL_FAST_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_REQUEST_FAULT_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_TRANSPORT_FAULT_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===529||OVERLOAD_TEXT.test(text)||status!==void 0&&status>=500&&status<600?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===408||NETWORK_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:{kind:"fail_request"}}var CredentialFailoverError=class extends Error{constructor(action,original,options={}){let detail=original instanceof Error?original.message:String(original);super(detail,{cause:original}),this.name="CredentialFailoverError",this.action=action,this.original=original,this.retryAt=options.retryAt}};function isAvailable(slot,now){return!(slot.blockReason==="account_disabled"||slot.blockedUntil!==void 0&&slot.blockedUntil>now)}function coolingProbe(slots,attempted){if(attempted.size>0)return[];let soonest=slots.filter(slot=>slot.blockReason==="rate_limit"&&slot.blockedUntil!==void 0).reduce((best,slot)=>best===void 0||(slot.blockedUntil??0)<(best.blockedUntil??0)?slot:best,void 0);return soonest===void 0?[]:[soonest]}function noSlotsMessage(slots,now){let blocked=slots.map(slot=>{let reason=slot.blockReason??"blocked";return slot.blockedUntil!==void 0&&slot.blockedUntil>now?`${slot.name} (${reason} until ${new Date(slot.blockedUntil).toISOString()})`:reason==="account_disabled"?`${slot.name} (account_disabled until re-login)`:`${slot.name} (${reason})`});return blocked.length===0?"No credential slots available":`No credential slots available: ${blocked.join(", ")}`}function soonestRetryAt(slots,now){let deadlines=slots.map(slot=>slot.blockedUntil).filter(value=>value!==void 0&&value>now);return deadlines.length===0?void 0:Math.min(...deadlines)}async function settle(stream){let iterator=stream[Symbol.asyncIterator]();try{await iterator.return?.(void 0)}catch{}}async function*runCredentialFailover(options){let now=options.now??Date.now,classify=options.classify??classifyCredentialFailure,attempted=new Set,retriesBySlot=new Map,lastError,lastOriginal,lastTerminalEvent,startAnnounced=!1;for(;;){let slots=await options.listSlots(),available=slots.filter(slot2=>!attempted.has(slot2.name)&&isAvailable(slot2,now())),candidates=available.length>0?available:coolingProbe(slots,attempted);if(candidates.length===0){if(lastTerminalEvent!==void 0){yield lastTerminalEvent;return}let retryAt=soonestRetryAt(slots,now());throw lastError!==void 0&&lastOriginal!==void 0?new CredentialFailoverError(lastError.action,lastOriginal,retryAt===void 0?{}:{retryAt}):new CredentialFailoverError({kind:"fail_request"},new Error(noSlotsMessage(slots,now())),retryAt===void 0?{}:{retryAt})}let slot=options.select(candidates),committedOutput=!1,terminalEvent,attemptStream;try{attemptStream=await options.runAttempt(slot);for await(let event of attemptStream){let failure=options.errorFromEvent?.(event);if(failure!==void 0)throw terminalEvent=event,failure;if(options.isStreamStart?.(event)){if(startAnnounced)continue;startAnnounced=!0}committedOutput||=options.isCommittedOutput(event),yield event}await options.onSuccess?.(slot);return}catch(error){attemptStream&&await settle(attemptStream);let failureCount=(slot.failureCount??0)+(retriesBySlot.get(slot.name)??0),action=classify(error,{failureCount});if(lastOriginal=error,lastTerminalEvent=terminalEvent,action.kind==="retry_same"&&!committedOutput){let used=(retriesBySlot.get(slot.name)??0)+1;if(retriesBySlot.set(slot.name,used),used<action.maxAttempts)continue;if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}if(action.kind!=="failover"){if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}await options.persistBlock(slot,action.block),attempted.add(slot.name);let failure=new CredentialFailoverError(action,error);if(lastError=failure,await options.onRotate?.({slot,block:action.block,attempt:attempted.size,committedOutput}),committedOutput){if(terminalEvent!==void 0){yield terminalEvent;return}throw failure}}}}function slotKind(slot){return slot.access!==void 0||slot.refresh!==void 0?"oauth":slot.key!==void 0?"api_key":void 0}function unusedSlotKinds(credential){if(!credential||!Array.isArray(credential.accounts))return[];let kinds=new Set;for(let slot of listSlots(credential)){let kind=slotKind(slot);kind!==void 0&&kind!==credential.type&&kinds.add(kind)}return[...kinds]}function slotsOfOwnKind(credential){return listSlots(credential).filter(slot=>slotKind(slot)!==otherKind(credential.type))}var otherKind=kind=>kind==="oauth"?"api_key":"oauth";var FileReferenceSchema=typebox_exports.Object({$file:typebox_exports.String({minLength:1})},{additionalProperties:!1}),EnvReferenceSchema=typebox_exports.Object({$env:typebox_exports.String({pattern:"^[A-Za-z_][A-Za-z0-9_]*$"})},{additionalProperties:!1}),ConcatReferenceSchema=typebox_exports.Object({$concat:typebox_exports.Array(typebox_exports.Union([typebox_exports.String(),FileReferenceSchema,EnvReferenceSchema]))},{additionalProperties:!1}),ConfigReferenceSchema=typebox_exports.Union([FileReferenceSchema,EnvReferenceSchema,ConcatReferenceSchema]),ConfigValueSchema=typebox_exports.Union([typebox_exports.String(),ConfigReferenceSchema]),NonemptyConfigValueSchema=typebox_exports.Union([typebox_exports.String({minLength:1}),ConfigReferenceSchema]),validateReference=Compile(ConfigReferenceSchema);function isConfigReference(value){return validateReference.Check(value)}function assertConfigValue(value,field){if(typeof value!="string"&&!isConfigReference(value))throw new ConfigReferenceError(field,value,"malformed")}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(new Error("Aborted"));return}let timeout=setTimeout(resolve,ms);signal?.addEventListener("abort",()=>{clearTimeout(timeout),reject(new Error("Aborted"))})})}var warnedVariables=new Set;function warnOpaqueConfigEnvironment(name,value){value!==void 0&&/\{(?:file|env):/.test(value)&&!warnedVariables.has(name)&&(warnedVariables.add(name),console.warn(`${name}: environment value contains reference-looking text; inserted literally`))}function warnMissingConfigEnvironment(name){warnedVariables.has(name)||(warnedVariables.add(name),console.warn(`${name}: configuration environment variable is unset`))}import{dirname as dirname2}from"node:path";import{constants}from"node:fs";import{lstat,open,readlink}from"node:fs/promises";import{homedir}from"node:os";import{dirname,isAbsolute,join,parse,sep}from"node:path";var MAX_BYTES=65536,readableWarnings=new Set;function fail(input,reason){throw new ConfigReferenceError(input.field,input.reference,reason)}function checkOwner(input,stat){process.platform!=="win32"&&stat.uid!==0&&stat.uid!==process.getuid?.()&&fail(input,"unsafe-owner")}function checkWritable(input,stat,ancestor){process.platform==="win32"||stat.isSymbolicLink()||(stat.mode&18)===0||ancestor&&stat.isDirectory()&&(stat.mode&512)!==0||fail(input,"unsafe-permissions")}function sameFile(left,right){return left.dev===right.dev&&left.ino===right.ino}function absolutePath(input){let declared=input.reference.$file;return declared.startsWith("~/")||process.platform==="win32"&&declared.startsWith("~\\")?`${homedir()}${sep}${declared.slice(2)}`:isAbsolute(declared)?declared:`${input.baseDir}${sep}${declared}`}async function walk(input){let absolute=absolutePath(input),current=parse(absolute).root,pending=absolute.slice(current.length).split(sep).filter(Boolean),stat=await lstat(current),links=0;checkOwner(input,stat),checkWritable(input,stat,!0);for(let part=pending.shift();part!==void 0;part=pending.shift()){if(part===".")continue;stat.isDirectory()||fail(input,"non-regular");let next=part===".."?dirname(current):join(current,part),nextStat=await lstat(next);if(checkOwner(input,nextStat),process.platform!=="win32"&&(stat.mode&18)!==0&&!nextStat.isSymbolicLink()&&(nextStat.mode&18)!==0&&fail(input,"unsafe-permissions"),checkWritable(input,nextStat,pending.length>0),nextStat.isSymbolicLink()){++links>40&&fail(input,"unreadable");let target=await readlink(next);sameFile(nextStat,await lstat(next))||fail(input,"changed");let targetPath=isAbsolute(target)?target:`${current}${sep}${target}`;current=parse(targetPath).root,pending=[...targetPath.slice(current.length).split(sep).filter(Boolean),...pending],stat=await lstat(current),checkOwner(input,stat),checkWritable(input,stat,!0)}else current=next,stat=nextStat}return stat.isFile()||fail(input,"non-regular"),{path:current,stat}}async function readConfigReferenceFile(input){try{let walked=await walk(input),flags=constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0),handle=await open(walked.path,flags);try{let stat=await handle.stat();sameFile(walked.stat,stat)||fail(input,"changed"),stat.isFile()||fail(input,"non-regular"),checkOwner(input,stat),checkWritable(input,stat,!1),stat.size>MAX_BYTES&&fail(input,"oversize");let buffer=Buffer.alloc(MAX_BYTES+1),length=0;for(;length<buffer.length;){let{bytesRead}=await handle.read(buffer,length,buffer.length-length,length);if(bytesRead===0)break;length+=bytesRead}length>MAX_BYTES&&fail(input,"oversize");let value;try{value=new TextDecoder("utf-8",{fatal:!0}).decode(buffer.subarray(0,length)).trim()}catch{fail(input,"invalid-utf8")}return value.length===0&&fail(input,"empty"),process.platform!=="win32"&&(stat.mode&36)!==0&&!readableWarnings.has(walked.path)&&(readableWarnings.add(walked.path),console.warn(`${input.field}: reference file is readable by other users`)),value}finally{await handle.close()}}catch(error){if(error instanceof ConfigReferenceError)throw error;let code=Reflect.get(Object(error),"code");fail(input,code==="ENOENT"||code==="ENOTDIR"?"missing":"unreadable")}}var origins=new WeakMap;function rememberConfigReferenceOrigin(value,context){typeof value!="string"&&origins.set(value,context)}function configReferenceContext(value,context){return context??(typeof value=="string"?void 0:origins.get(value))}function assertConfigReferenceAuthority(value,context){if(typeof value=="string")return;let source=configReferenceContext(value,context);if(source?.authority!=="trusted")throw new ConfigReferenceError(source?.field??"configuration value",value,"forbidden");assertConfigValue(value,source.field)}async function resolveConfigReference(value,context,env){let source=configReferenceContext(value,context);if(assertConfigReferenceAuthority(value,source),source===void 0)throw new ConfigReferenceError("configuration value",value,"forbidden");if("$file"in value){let text=await readConfigReferenceFile({field:source.field,reference:value,baseDir:source.baseDir??dirname2(source.origin)});return rememberResolvedReferenceValue(text),text}if("$env"in value){let result2=(env??source.env??process.env)[value.$env];if(warnOpaqueConfigEnvironment(value.$env,result2),result2===void 0)throw new ConfigReferenceError(source.field,value,"unset");if(result2==="")throw new ConfigReferenceError(source.field,value,"empty");return rememberResolvedReferenceValue(result2),result2}let parts=[];for(let part of value.$concat)parts.push(typeof part=="string"?part:await resolveConfigReference(part,source,env));let result=parts.join("");if(result==="")throw new ConfigReferenceError(source.field,value,"empty");return rememberResolvedReferenceValue(result),result}import{spawn}from"child_process";var COMMAND_EXECUTION_MAX_ATTEMPTS=3,COMMAND_EXECUTION_BACKOFF_MS=[250,1e3],COMMAND_TIMEOUT_MS=1e4,COMMAND_MAX_OUTPUT_BYTES=1024*1024;function runCommandProcess(file,args,options){return new Promise(resolveOutcome=>{let spawnOptions={shell:options.shell,windowsHide:!0,...options.env===void 0?{}:{env:{...process.env,...options.env}}},child=options.stdin===void 0?spawn(file,[...args],{...spawnOptions,stdio:["ignore","pipe","ignore"]}):spawn(file,[...args],{...spawnOptions,stdio:["pipe","pipe","ignore"]}),stdout="",settled=!1,finish=outcome=>{settled||(settled=!0,clearTimeout(timer),resolveOutcome(outcome))},timer=setTimeout(()=>{signalSpawnedChild(child,"SIGTERM"),child.unref(),finish({executed:!0,value:void 0})},COMMAND_TIMEOUT_MS);child.stdout.setEncoding("utf-8"),child.stdout.on("data",chunk=>{stdout+=chunk,!(stdout.length<=COMMAND_MAX_OUTPUT_BYTES)&&(signalSpawnedChild(child,"SIGTERM"),finish({executed:!0,value:void 0}))}),child.on("error",error=>finish({executed:error.code!=="ENOENT",value:void 0})),child.on("close",code=>{let value=stdout.trim();finish({executed:!0,value:code===0&&value?value:void 0})}),child.stdin?.end(options.stdin)})}async function executeWithConfiguredShell(command,env){try{let{shell,args,commandTransport}=getShellConfig(),commandFromStdin=commandTransport==="stdin";return await runCommandProcess(shell,commandFromStdin?args:[...args,command],{shell:!1,...commandFromStdin?{stdin:command}:{},...env===void 0?{}:{env}})}catch{return{executed:!1,value:void 0}}}async function executeCommandOnce(command,env){if(process.platform==="win32"){let configured=await executeWithConfiguredShell(command,env);if(configured.executed)return configured.value}return(await runCommandProcess(command,[],{shell:!0,...env===void 0?{}:{env}})).value}async function runConfigCommand(commandConfig,env){let command=commandConfig.slice(1);for(let attempt=0;attempt<COMMAND_EXECUTION_MAX_ATTEMPTS;attempt++){let value=await executeCommandOnce(command,env);if(value!==void 0)return value;let backoffMs=COMMAND_EXECUTION_BACKOFF_MS[attempt];backoffMs!==void 0&&await sleep(backoffMs)}}var commandResultCache=new Map,ENV_VAR_NAME_RE=/^[A-Za-z_][A-Za-z0-9_]*$/,ENV_VAR_NAME_PREFIX_RE=/^[A-Za-z_][A-Za-z0-9_]*/;function appendLiteral(parts,value){if(!value)return;let previousPart=parts[parts.length-1];if(previousPart?.type==="literal"){previousPart.value+=value;return}parts.push({type:"literal",value})}function parseConfigValueTemplate(config){let parts=[],index=0;for(;index<config.length;){let dollarIndex=config.indexOf("$",index);if(dollarIndex<0){appendLiteral(parts,config.slice(index));break}appendLiteral(parts,config.slice(index,dollarIndex));let nextChar=config[dollarIndex+1];if(nextChar==="$"||nextChar==="!"){appendLiteral(parts,nextChar),index=dollarIndex+2;continue}if(nextChar==="{"){let endIndex=config.indexOf("}",dollarIndex+2);if(endIndex<0){appendLiteral(parts,"$"),index=dollarIndex+1;continue}let name=config.slice(dollarIndex+2,endIndex);ENV_VAR_NAME_RE.test(name)?parts.push({type:"env",name}):appendLiteral(parts,config.slice(dollarIndex,endIndex+1)),index=endIndex+1;continue}let match=config.slice(dollarIndex+1).match(ENV_VAR_NAME_PREFIX_RE);if(match){parts.push({type:"env",name:match[0]}),index=dollarIndex+1+match[0].length;continue}appendLiteral(parts,"$"),index=dollarIndex+1}return parts}function parseConfigValueReference(config){return config.startsWith("!")?{type:"command",config}:{type:"template",parts:parseConfigValueTemplate(config)}}function resolveEnvConfigValue(name,env){let value=env?.[name]||process.env[name]||void 0;return warnOpaqueConfigEnvironment(name,value),value}function getTemplateEnvVarNames(parts){let names=[];for(let part of parts)part.type!=="env"||names.includes(part.name)||names.push(part.name);return names}function resolveTemplate(parts,env){let resolved="";for(let part of parts){if(part.type==="literal"){resolved+=part.value;continue}let envValue=resolveEnvConfigValue(part.name,env);if(envValue===void 0){warnMissingConfigEnvironment(part.name);return}resolved+=envValue}return resolved}function getConfigValueEnvVarNames(config){if(typeof config!="string")return"$env"in config?[config.$env]:"$concat"in config?[...new Set(config.$concat.flatMap(part=>typeof part!="string"&&"$env"in part?[part.$env]:[]))]:[];let reference=parseConfigValueReference(config);return reference.type==="template"?getTemplateEnvVarNames(reference.parts):[]}function getMissingConfigValueEnvVarNames(config,env){return getConfigValueEnvVarNames(config).filter(name=>resolveEnvConfigValue(name,env)===void 0)}function isCommandConfigValue(config){return typeof config=="string"&&parseConfigValueReference(config).type==="command"}function isConfigValueConfigured(config,env){return typeof config!="string"||getMissingConfigValueEnvVarNames(config,env).length===0}function resolveConfigValue(config,env,context){if(typeof config!="string")return resolveConfigReference(config,context,env);let reference=parseConfigValueReference(config);return reference.type==="command"?env===void 0?executeCommand(reference.config):runConfigCommand(reference.config,env):Promise.resolve(resolveTemplate(reference.parts,env))}function executeCommand(commandConfig){let cached=commandResultCache.get(commandConfig);if(cached)return cached;let result=runConfigCommand(commandConfig);return commandResultCache.set(commandConfig,result),result}function resolveConfigValueUncached(config,env,context){if(typeof config!="string")return resolveConfigReference(config,context,env);let reference=parseConfigValueReference(config);return reference.type==="command"?runConfigCommand(reference.config,env):Promise.resolve(resolveTemplate(reference.parts,env))}async function resolveConfigValueOrThrow(config,description,env,context){if(typeof config!="string")return resolveConfigReference(config,context,env);let resolvedValue=await resolveConfigValueUncached(config,env,context);if(resolvedValue!==void 0)return resolvedValue;let reference=parseConfigValueReference(config);if(reference.type==="command")throw new Error(`Failed to resolve ${description} from shell command: ${reference.config.slice(1)}`);if(reference.type==="template"){let missingEnvVars=getMissingConfigValueEnvVarNames(config,env);if(missingEnvVars.length===1)throw new Error(`Failed to resolve ${description} from environment variable: ${missingEnvVars[0]}`);if(missingEnvVars.length>1)throw new Error(`Failed to resolve ${description} from environment variables: ${missingEnvVars.join(", ")}`)}throw new Error(`Failed to resolve ${description}`)}async function resolveHeadersOrThrow(headers,description,env){if(!headers)return;for(let value of Object.values(headers))assertConfigReferenceAuthority(value);let resolved={};for(let[key,value]of Object.entries(headers))resolved[key]=await resolveConfigValueOrThrow(value,`${description} header "${key}"`,env);return Object.keys(resolved).length>0?resolved:void 0}export{slotKind,unusedSlotKinds,slotsOfOwnKind,rendezvousOrder,applyAccountOrder,withoutOrderedAccount,ConfigValueSchema,NonemptyConfigValueSchema,isConfigReference,warnOpaqueConfigEnvironment,warnMissingConfigEnvironment,rememberConfigReferenceOrigin,assertConfigReferenceAuthority,resolveConfigReference,sleep,getConfigValueEnvVarNames,isCommandConfigValue,isConfigValueConfigured,resolveConfigValue,resolveConfigValueOrThrow,resolveHeadersOrThrow,isCommittedRotationOutput,isRotationStreamStart,rotationErrorFromEvent,MAX_SLOT_BLOCK_MS,ACCOUNT_POOL_REFUSAL_NOTE,classifyCredentialFailure,CredentialFailoverError,runCredentialFailover};
@@ -1,2 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- var FAMILY_KEY=/^(?:opus|sonnet|haiku|fable|mythos)$/,MODEL_FAMILY_LIMIT=/\b(opus|sonnet|haiku|fable|mythos)(?:\s+\d+(?:\.\d+)?)?(?:\s+(?:weekly|daily|monthly|session|\d+-hour))?\s+limit\b/i;function rateLimitModelFamily(text){return MODEL_FAMILY_LIMIT.exec(text)?.[1]?.toLowerCase()}function inFamily(modelId,family){return new RegExp(`(?:^|[^a-z])${family}(?:[^a-z]|$)`,"i").test(modelId)}function modelBlockKey(family,modelId){return inFamily(modelId,family)?family:modelId}function applies(key,modelId){return key===modelId||FAMILY_KEY.test(key)&&inFamily(modelId,key)}function activeModelBlockUntil(blocks,modelId,now){if(blocks===void 0||modelId===void 0)return;let until;for(let[key,block]of Object.entries(blocks))block.blockedUntil>now&&applies(key,modelId)&&(until===void 0||block.blockedUntil>until)&&(until=block.blockedUntil);return until}function pruneModelBlocks(blocks,now,servedModelId){if(blocks===void 0)return;let kept=Object.entries(blocks).filter(([key,block])=>block.blockedUntil>now&&(servedModelId===void 0||!applies(key,servedModelId)));return kept.length===0?void 0:Object.fromEntries(kept)}function withModelBlock(blocks,key,blockedUntil,now){return mergeModelBlocks(pruneModelBlocks(blocks,now),{[key]:{blockedUntil}},now)??{}}function mergeModelBlocks(left,right,now){let merged=new Map(Object.entries(pruneModelBlocks(left,now)??{}));for(let[key,block]of Object.entries(pruneModelBlocks(right,now)??{}))merged.set(key,{blockedUntil:Math.max(merged.get(key)?.blockedUntil??0,block.blockedUntil)});return merged.size===0?void 0:Object.fromEntries(merged)}function describeModelBlocks(blocks,now){return Object.entries(pruneModelBlocks(blocks,now)??{}).map(([key,block])=>`blocked for ${key} until ${new Date(block.blockedUntil).toISOString()}`)}var MONTHS=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],RESET_AT_KEYS=new Set(["resets_at"]),RESET_AFTER_SECONDS_KEYS=new Set(["reset_after_seconds"]),RELATIVE_RE=/\b(?:resets?|try again|retry)\s+in\s+~?((?:\d+(?:\.\d+)?\s*(?:days?|d|hours?|hrs?|h|minutes?|mins?|m|seconds?|secs?|s)\b(?:\s*,?\s*(?:and\s+)?)?)+)/i,RELATIVE_PART_RE=/(\d+(?:\.\d+)?)\s*(days?|d|hours?|hrs?|h|minutes?|mins?|m|seconds?|secs?|s)\b/gi,CLOCK_RE=/\b(?:resets?|try again)\s+(?:at\s+|on\s+)?(?:([a-z]{3})[a-z]*\.?\s+(\d{1,2}),?\s+(?:at\s+)?)?(\d{1,2})(?::(\d{2}))?\s*([ap])\.?\s?m\b\.?(?:\s*\(([A-Za-z_]+(?:\/[A-Za-z0-9_+-]+)*)\))?/i;function usageLimitResetMs(text,nowMs){return usageLimitReset(text,nowMs)?.ms}function usageLimitReset(text,nowMs){let json=fromJsonFields(text,nowMs);if(json!==void 0)return{ms:json,kind:"absolute"};let relative=fromRelativeProse(text);if(relative!==void 0)return{ms:relative,kind:"relative"};let clock=fromClockProse(text,nowMs);return clock===void 0?void 0:{ms:clock,kind:"absolute"}}function fromJsonFields(text,nowMs){let start=text.indexOf("{");if(start<0)return;let parsed;try{parsed=JSON.parse(text.slice(start))}catch{return}let found;return walk(parsed,(key,value)=>{let ms=RESET_AT_KEYS.has(key)?absoluteFieldMs(value,nowMs):RESET_AFTER_SECONDS_KEYS.has(key)?secondsFieldMs(value):void 0;ms!==void 0&&(found===void 0||ms>found)&&(found=ms)}),found}function walk(value,visit){if(Array.isArray(value)){for(let item of value)walk(item,visit);return}if(!(typeof value!="object"||value===null))for(let[key,entry]of Object.entries(value))visit(key,entry),walk(entry,visit)}function absoluteFieldMs(value,nowMs){if(typeof value=="number"&&Number.isFinite(value)&&value>0){let epochMs=value<1e12?value*1e3:value;return Math.max(0,Math.ceil(epochMs-nowMs))}if(typeof value=="string"&&/\d{4}-\d{2}-\d{2}T/.test(value)){let epochMs=Date.parse(value);return Number.isNaN(epochMs)?void 0:Math.max(0,epochMs-nowMs)}}function secondsFieldMs(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0?Math.ceil(value*1e3):void 0}function fromRelativeProse(text){let phrase=RELATIVE_RE.exec(text)?.[1];if(phrase===void 0)return;let total=0;for(let[,amount,unit]of phrase.matchAll(RELATIVE_PART_RE))total+=Number.parseFloat(amount??"0")*unitMs(unit??"");return Math.ceil(total)}function unitMs(unit){let u=unit.toLowerCase();return u.startsWith("d")?864e5:u.startsWith("h")?36e5:u==="s"||u.startsWith("sec")?1e3:6e4}function fromClockProse(text,nowMs){let match=CLOCK_RE.exec(text);if(!match)return;let[,monthName,dayText,hourText,minuteText,meridiem,zoneText]=match,hour12=Number.parseInt(hourText??"",10),minute=minuteText===void 0?0:Number.parseInt(minuteText,10);if(hour12<1||hour12>12||minute>59)return;let hour=hour12%12+(meridiem?.toLowerCase()==="p"?12:0),zone=zoneText??Intl.DateTimeFormat().resolvedOptions().timeZone;if(!isValidTimeZone(zone))return;let today=zonedParts(zone,nowMs);if(monthName!==void 0){let month=MONTHS.indexOf(monthName.toLowerCase()),day=Number.parseInt(dayText??"",10);if(month<0||day<1||day>31)return;let target2=zonedToEpoch(zone,today.year,month,day,hour,minute);return target2<=nowMs&&(target2=zonedToEpoch(zone,today.year+1,month,day,hour,minute)),target2-nowMs}let target=zonedToEpoch(zone,today.year,today.month,today.day,hour,minute);return target<=nowMs&&(target=zonedToEpoch(zone,today.year,today.month,today.day+1,hour,minute)),target-nowMs}function isValidTimeZone(zone){try{return new Intl.DateTimeFormat("en-US",{timeZone:zone}),!0}catch{return!1}}function zonedParts(zone,epochMs){let parts=new Intl.DateTimeFormat("en-US",{timeZone:zone,hourCycle:"h23",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}).formatToParts(epochMs),get=type=>Number.parseInt(parts.find(part=>part.type===type)?.value??"0",10);return{year:get("year"),month:get("month")-1,day:get("day"),hour:get("hour"),minute:get("minute"),second:get("second")}}function zoneOffsetMs(zone,epochMs){let p=zonedParts(zone,epochMs);return Date.UTC(p.year,p.month,p.day,p.hour,p.minute,p.second)-Math.floor(epochMs/1e3)*1e3}function zonedToEpoch(zone,year,month,day,hour,minute){let wall=Date.UTC(year,month,day,hour,minute),first=wall-zoneOffsetMs(zone,wall);return wall-zoneOffsetMs(zone,first)}export{usageLimitResetMs,usageLimitReset,rateLimitModelFamily,modelBlockKey,activeModelBlockUntil,pruneModelBlocks,withModelBlock,mergeModelBlocks,describeModelBlocks};
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
3
- import"./chunk-MYAENL22.js";import{enableStartupCompileCache}from"./chunk-MJ5NNWX4.js";import"./chunk-UFJ2K7Q7.js";import{installStaleExtensionContainment,main}from"./chunk-YRF4I43T.js";import"./chunk-ODTGC6YU.js";import"./chunk-FHXR4ZAC.js";import"./chunk-7CNOCJCN.js";import{configureHttpDispatcher}from"./chunk-FFQOEC76.js";import"./chunk-DXJJP6RP.js";import"./chunk-GXY5JEI5.js";import"./chunk-7W7OJDIY.js";import"./chunk-GY5MR5KR.js";import"./chunk-EHQXLHRB.js";import"./chunk-XF3LJC3O.js";import"./chunk-CNPDUC4D.js";import"./chunk-MLVIYDHK.js";import"./chunk-H3HNMY2W.js";import"./chunk-JPGT64RV.js";import"./chunk-UQNRW3VU.js";import"./chunk-P3M2PF6K.js";import"./chunk-HVJI5T75.js";import"./chunk-QMRJYMNH.js";import"./chunk-C5UFJ7B3.js";import"./chunk-TIVW4P37.js";import"./chunk-H4QOEVS5.js";import"./chunk-3LNSLJ7N.js";import"./chunk-MSQCTH6V.js";import"./chunk-4AOMNOGY.js";import"./chunk-KLAX467B.js";import"./chunk-JFFS72FL.js";import"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-SOMFLLPD.js";import"./chunk-WD6WBYC5.js";import"./chunk-26UBFF6N.js";import"./chunk-MTQQ2VQH.js";import"./chunk-JA2R2ZSE.js";import"./chunk-Z3UYNSVR.js";import"./chunk-KXB5WIS5.js";import"./chunk-CNL6QSUB.js";import"./chunk-SWJXRC2I.js";import"./chunk-4WZRVZNX.js";import"./chunk-U3VOXCGP.js";import"./chunk-O3Q2ET6W.js";import"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-3BTN337S.js";import"./chunk-QXREUA5F.js";import"./chunk-RUGYFYH7.js";import"./chunk-OEFCY46F.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-TTU2RNVX.js";import"./chunk-FDL4CF6F.js";import"./chunk-BWA4FVFW.js";import"./chunk-YU4AYH4C.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-WLHNEUGD.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-V3CK2AVC.js";import"./chunk-VRDU425E.js";import"./chunk-ZGAB7WQA.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-QN2BHP3M.js";import"./chunk-NTK2MHJ5.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";await enableStartupCompileCache();installEarlyInspectorVmImportRecovery();installStaleExtensionContainment();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();await main(process.argv.slice(2));
@@ -1,2 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader}from"./chunk-YRF4I43T.js";import"./chunk-ODTGC6YU.js";import"./chunk-FHXR4ZAC.js";import"./chunk-7CNOCJCN.js";import"./chunk-FFQOEC76.js";import"./chunk-DXJJP6RP.js";import"./chunk-GXY5JEI5.js";import"./chunk-7W7OJDIY.js";import"./chunk-GY5MR5KR.js";import"./chunk-EHQXLHRB.js";import"./chunk-XF3LJC3O.js";import"./chunk-CNPDUC4D.js";import"./chunk-MLVIYDHK.js";import"./chunk-H3HNMY2W.js";import"./chunk-JPGT64RV.js";import"./chunk-UQNRW3VU.js";import"./chunk-P3M2PF6K.js";import"./chunk-HVJI5T75.js";import"./chunk-QMRJYMNH.js";import"./chunk-C5UFJ7B3.js";import"./chunk-TIVW4P37.js";import"./chunk-H4QOEVS5.js";import"./chunk-3LNSLJ7N.js";import"./chunk-MSQCTH6V.js";import"./chunk-4AOMNOGY.js";import"./chunk-KLAX467B.js";import"./chunk-JFFS72FL.js";import"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-SOMFLLPD.js";import"./chunk-WD6WBYC5.js";import"./chunk-26UBFF6N.js";import"./chunk-MTQQ2VQH.js";import"./chunk-JA2R2ZSE.js";import"./chunk-Z3UYNSVR.js";import"./chunk-KXB5WIS5.js";import"./chunk-CNL6QSUB.js";import"./chunk-SWJXRC2I.js";import"./chunk-4WZRVZNX.js";import"./chunk-U3VOXCGP.js";import"./chunk-O3Q2ET6W.js";import"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-3BTN337S.js";import"./chunk-QXREUA5F.js";import"./chunk-RUGYFYH7.js";import"./chunk-OEFCY46F.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-TTU2RNVX.js";import"./chunk-FDL4CF6F.js";import"./chunk-BWA4FVFW.js";import"./chunk-YU4AYH4C.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import"./chunk-WLHNEUGD.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-V3CK2AVC.js";import"./chunk-VRDU425E.js";import"./chunk-ZGAB7WQA.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-QN2BHP3M.js";import"./chunk-NTK2MHJ5.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader};
@@ -1,2 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{STORE_BUSY,writeHealthUnlessStoreBusy}from"./chunk-OX5QL4YF.js";import{applyAccountOrder,classifyCredentialFailure,getConfigValueEnvVarNames,isCommittedRotationOutput,isRotationStreamStart,rendezvousOrder,resolveConfigValue,rotationErrorFromEvent,runCredentialFailover,slotsOfOwnKind}from"./chunk-3LNSLJ7N.js";import{activeModelBlockUntil,modelBlockKey,pruneModelBlocks,withModelBlock}from"./chunk-MSQCTH6V.js";import{discoverEnvSlots}from"./chunk-4AOMNOGY.js";import"./chunk-KLAX467B.js";import{acquireHalfOpenLease}from"./chunk-JFFS72FL.js";import"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-BWA4FVFW.js";import"./chunk-YU4AYH4C.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import{ConfigReferenceError}from"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";import{createHash,randomUUID}from"node:crypto";async function releaseLeaseIfModelBlocked(repository,providerId,lane,slotName,leaseId,until){until!==void 0&&await writeHealthUnlessStoreBusy(`lease release on ${slotName}`,()=>repository.mutateSlotState(providerId,lane,slotName,current=>{if(current?.lease?.id!==leaseId)return current;let{lease:_released,...rest}=current;return rest}))}function probeLease(repository,providerId,lane,slotName,now){return writeHealthUnlessStoreBusy(`probe lease on ${slotName}`,()=>acquireHalfOpenLease(repository,providerId,lane,slotName,{now}))}function overlayState(slot,state){return state?{...slot,...state.blockedUntil===void 0?{}:{blockedUntil:state.blockedUntil},...state.blockReason===void 0?{}:{blockReason:state.blockReason},...state.failureCount===void 0?{}:{failureCount:state.failureCount},...state.lease===void 0?{}:{lease:state.lease}}:slot}function overlayModelBlock(slot,until){return until===void 0||slot.blockedUntil!==void 0&&slot.blockedUntil>=until?slot:{...slot,blockedUntil:until,blockReason:slot.blockReason??"rate_limit"}}var warnedSlotReferences=new Set;async function listRotationSlots(sources,options={}){let acquireLeases=options.acquireLeases!==!1,modelId=options.modelId,now=sources.now??Date.now,{providerId,credential,env,repository}=sources,policySlots=[],referenceError;for(let[name,ref]of Object.entries(sources.policy?.slots??{})){let envVarName=ref.env??`models.json:${name}`,key;try{key=ref.env!==void 0?env(ref.env):ref.value!==void 0?await resolveConfigValue(ref.value,typeof ref.value=="string"?{}:Object.fromEntries(getConfigValueEnvVarNames(ref.value).flatMap(variable=>{let value=env(variable);return value===void 0?[]:[[variable,value]]}))):void 0}catch(error){if(!(error instanceof ConfigReferenceError))throw error;let notice=`${error.field}: configuration reference ${error.reason}; skipping credential slot`;warnedSlotReferences.has(notice)||(warnedSlotReferences.add(notice),console.warn(notice)),referenceError??=error;continue}key&&policySlots.push({name,envVarName,key,source:"env"})}if(credential){let state=await repository.listSlots(providerId,"stored"),slots=[];for(let slot of slotsOfOwnKind(credential)){let persisted=state[slot.name],storedRevision=await repository.storedCredentialRevision(providerId,slot.name,{key:slot.key,access:slot.access,refresh:slot.refresh}),applicable=persisted?.credentialRevision===storedRevision?persisted:void 0,modelUntil=activeModelBlockUntil(applicable?.modelBlocks,modelId,now()),lease;if(!(acquireLeases&&modelUntil===void 0&&applicable?.blockedUntil!==void 0&&applicable.blockedUntil<=now()&&(lease=await probeLease(repository,providerId,"stored",slot.name,now()),lease===void 0))){if(lease!==void 0&&lease!==STORE_BUSY){let leasedState=(await repository.listSlots(providerId,"stored"))[slot.name],leasedApplicable=leasedState?.credentialRevision===storedRevision?leasedState:void 0,leasedModelUntil=activeModelBlockUntil(leasedApplicable?.modelBlocks,modelId,now());await releaseLeaseIfModelBlocked(repository,providerId,"stored",slot.name,lease.leaseId,leasedModelUntil),slots.push(overlayModelBlock(overlayState({name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision},leasedApplicable),leasedModelUntil));continue}slots.push(overlayModelBlock(overlayState({name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision},applicable),modelUntil))}}if(policySlots.length===0){if(slots.length===0&&referenceError!==void 0)throw referenceError;return slots}let namedSources={...sources,credential:void 0,policy:{...sources.policy,slots:{}}},namedSlots=await listEnvRotationSlots(namedSources,policySlots,acquireLeases,modelId);return[...slots,...namedSlots]}let envSlots=[...discoverEnvSlots(providerId,env),...policySlots];if(envSlots.length===0&&referenceError!==void 0)throw referenceError;return listEnvRotationSlots(sources,envSlots,acquireLeases,modelId)}async function listEnvRotationSlots(sources,envSlots,acquireLeases,modelId){if(envSlots.length===0)return[];let{providerId,repository}=sources,now=sources.now??Date.now,state=await repository.listSlots(providerId,"env"),slots=[];for(let slot of envSlots){let persisted=state[slot.name],revision=await repository.envCredentialRevision(slot.envVarName,slot.key),applicable=persisted?.credentialRevision===revision?persisted:void 0,modelUntil=activeModelBlockUntil(applicable?.modelBlocks,modelId,now());if(acquireLeases&&modelUntil===void 0&&applicable?.blockedUntil!==void 0&&applicable.blockedUntil<=now()){let lease=await probeLease(repository,providerId,"env",slot.name,now());if(lease===void 0)continue;if(lease!==STORE_BUSY){let leasedState=(await repository.listSlots(providerId,"env"))[slot.name];applicable=leasedState?.credentialRevision===revision?leasedState:void 0,modelUntil=activeModelBlockUntil(applicable?.modelBlocks,modelId,now()),await releaseLeaseIfModelBlocked(repository,providerId,"env",slot.name,lease.leaseId,modelUntil)}}slots.push(overlayModelBlock(overlayState({name:slot.name,lane:"env",envKey:slot.key,envVarName:slot.envVarName},applicable),modelUntil))}return slots}var sha256SlotHasher=input=>createHash("sha256").update(input).digest().readBigUInt64BE(0);function modelBlockPatch(family,modelId,blockedUntil,current,now,credentialRevision){let sameMaterial=current!==void 0&&current.credentialRevision===credentialRevision,{stateVersion:_stateVersion,...kept}=sameMaterial?current:{stateVersion:0};return{...kept,lease:void 0,...credentialRevision===void 0?{}:{credentialRevision},modelBlocks:withModelBlock(sameMaterial?current.modelBlocks:void 0,modelBlockKey(family,modelId),blockedUntil,now)}}function blockPatch(block,current,now,credentialRevision,policy,modelId){if(block.reason==="rate_limit"&&block.modelFamily!==void 0&&modelId!==void 0){let blockedUntil=now+Math.min(policy?.cooldownCapMs??block.cooldownMs,block.cooldownMs);return modelBlockPatch(block.modelFamily,modelId,blockedUntil,current,now,credentialRevision)}let failureCount=(current?.failureCount??0)+1,liveModelBlocks=current?.credentialRevision===credentialRevision?pruneModelBlocks(current?.modelBlocks,now):void 0,base={failureCount,...credentialRevision===void 0?{}:{credentialRevision},...current?.lastSuccessAt===void 0?{}:{lastSuccessAt:current.lastSuccessAt},...liveModelBlocks===void 0?{}:{modelBlocks:liveModelBlocks}};return block.reason==="rate_limit"?{...base,blockedUntil:now+Math.min(policy?.cooldownCapMs??block.cooldownMs,block.cooldownMs),blockReason:"rate_limit"}:block.reason==="auth_error"?{...base,blockedUntil:now+9e5,blockReason:"auth_error"}:{...base,blockReason:block.reason}}function streamWithCredentialRotation(options){let{sources,runAttempt}=options,hasher=options.hasher??sha256SlotHasher,affinityKey=options.affinityKey??randomUUID(),useAffinity=sources.policy?.affinity!==!1,pooled=sources.credential,now=sources.now??Date.now;return runCredentialFailover({listSlots:()=>listRotationSlots(sources,options.modelId===void 0?{}:{modelId:options.modelId}),select:candidates=>{let pinned=candidates.find(candidate=>candidate.pinned===!0);if(pinned)return pinned;let ranked=useAffinity?rendezvousOrder(affinityKey,candidates,hasher):candidates,winner=applyAccountOrder(pooled?.order,ranked)[0];if(!winner)throw new Error("credential rotation selected from an empty candidate set");return winner},runAttempt,isCommittedOutput:isCommittedRotationOutput,isStreamStart:isRotationStreamStart,errorFromEvent:rotationErrorFromEvent,classify:(error,context)=>classifyCredentialFailure(error,{...context,nowMs:now(),cooldownBaseMs:sources.policy?.cooldownBaseMs,cooldownCapMs:sources.policy?.cooldownCapMs}),onSuccess:async slot=>{await writeHealthUnlessStoreBusy(`success on ${slot.name}`,()=>sources.repository.mutateSlotState(sources.providerId,slot.lane,slot.name,current=>current?{...current,lastSuccessAt:now(),lease:void 0,blockedUntil:void 0,blockReason:void 0,failureCount:void 0,modelBlocks:pruneModelBlocks(current.modelBlocks,now(),options.modelId)}:void 0))},persistBlock:async(slot,block)=>{let revision=slot.lane==="env"&&slot.envVarName!==void 0&&slot.envKey!==void 0?await sources.repository.envCredentialRevision(slot.envVarName,slot.envKey):slot.storedRevision;await writeHealthUnlessStoreBusy(`${block.reason} block on ${slot.name}`,()=>sources.repository.mutateSlotState(sources.providerId,slot.lane,slot.name,current=>blockPatch(block,current,now(),revision,sources.policy,options.modelId)))},now})}export{listRotationSlots,sha256SlotHasher,streamWithCredentialRotation};
@@ -1,2 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{runRpcMode}from"./chunk-YRF4I43T.js";import"./chunk-ODTGC6YU.js";import"./chunk-FHXR4ZAC.js";import"./chunk-7CNOCJCN.js";import"./chunk-FFQOEC76.js";import"./chunk-DXJJP6RP.js";import"./chunk-GXY5JEI5.js";import"./chunk-7W7OJDIY.js";import"./chunk-GY5MR5KR.js";import"./chunk-EHQXLHRB.js";import"./chunk-XF3LJC3O.js";import"./chunk-CNPDUC4D.js";import"./chunk-MLVIYDHK.js";import"./chunk-H3HNMY2W.js";import"./chunk-JPGT64RV.js";import"./chunk-UQNRW3VU.js";import"./chunk-P3M2PF6K.js";import"./chunk-HVJI5T75.js";import"./chunk-QMRJYMNH.js";import"./chunk-C5UFJ7B3.js";import"./chunk-TIVW4P37.js";import"./chunk-H4QOEVS5.js";import"./chunk-3LNSLJ7N.js";import"./chunk-MSQCTH6V.js";import"./chunk-4AOMNOGY.js";import"./chunk-KLAX467B.js";import"./chunk-JFFS72FL.js";import"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-SOMFLLPD.js";import"./chunk-WD6WBYC5.js";import"./chunk-26UBFF6N.js";import"./chunk-MTQQ2VQH.js";import"./chunk-JA2R2ZSE.js";import"./chunk-Z3UYNSVR.js";import"./chunk-KXB5WIS5.js";import"./chunk-CNL6QSUB.js";import"./chunk-SWJXRC2I.js";import"./chunk-4WZRVZNX.js";import"./chunk-U3VOXCGP.js";import"./chunk-O3Q2ET6W.js";import"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-3BTN337S.js";import"./chunk-QXREUA5F.js";import"./chunk-RUGYFYH7.js";import"./chunk-OEFCY46F.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-TTU2RNVX.js";import"./chunk-FDL4CF6F.js";import"./chunk-BWA4FVFW.js";import"./chunk-YU4AYH4C.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import"./chunk-WLHNEUGD.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-V3CK2AVC.js";import"./chunk-VRDU425E.js";import"./chunk-ZGAB7WQA.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-QN2BHP3M.js";import"./chunk-NTK2MHJ5.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";export{runRpcMode};
@@ -1,3 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{SessionEventWriter,answerSubscribeSessions,answerUnsubscribeSessions,refusal,sessionRuntimeView,socketSink}from"./chunk-6O4SEW2W.js";import{WakeScheduler,answeredUiRequestId,availableModelsData,buildRpcSessionState,interruptRunningTurn,onProcessContinue,rpcCommandShapeError,runGetEffectStatus,settledQuestionStatus,subscribeSessionRecords,unansweredQuestionIds,unsupportedThinkingLevel,watchInbox}from"./chunk-7W7OJDIY.js";import"./chunk-GY5MR5KR.js";import"./chunk-EHQXLHRB.js";import"./chunk-XF3LJC3O.js";import"./chunk-CNPDUC4D.js";import"./chunk-MLVIYDHK.js";import"./chunk-JPGT64RV.js";import{SESSION_STATUS_CAPABILITY,acquireHostEnsureLock,engineBuildIdentity,gcHostEndpoints}from"./chunk-HVJI5T75.js";import"./chunk-QMRJYMNH.js";import"./chunk-C5UFJ7B3.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-SOMFLLPD.js";import"./chunk-WD6WBYC5.js";import"./chunk-26UBFF6N.js";import"./chunk-JA2R2ZSE.js";import{tuiSocketName}from"./chunk-Z3UYNSVR.js";import{thisProcessStartTime,writeHostRegistration}from"./chunk-SWJXRC2I.js";import{createDaemonDirectories,createHostDaemonPaths}from"./chunk-4WZRVZNX.js";import"./chunk-U3VOXCGP.js";import"./chunk-O3Q2ET6W.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-RUGYFYH7.js";import"./chunk-KRNXUTZJ.js";import"./chunk-FDL4CF6F.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-YU2P3CAR.js";import{MAX_SOCKET_PATH_BYTES}from"./chunk-VRDU425E.js";import{authenticateSocket,createSocketSecret,socketSecretPath}from"./chunk-ZGAB7WQA.js";import{VERSION}from"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";import{randomUUID as randomUUID2}from"node:crypto";import{rm as rm2}from"node:fs/promises";var ControlAttachments=class{constructor(session,pendingQuestions){this.writer=new SessionEventWriter(()=>{}),this.attached=new Set,this.session=session,this.writer.status.setSource({sessionIds:()=>[this.handle],entryView:id=>id===this.handle?this.entryView():void 0,view:id=>id===this.handle?{entry:this.entryView(),runtime:sessionRuntimeView(session,pendingQuestions())}:void 0}),this.writer.registerConnection(NULL_CONNECTION,{writeRaw:()=>{},waitForBackpressure:async()=>{}}),this.stopRecords=subscribeSessionRecords(session,record=>this.writer.enqueue(this.handle,record))}get handle(){return this.session.sessionId}opened(connection){this.writer.registerConnection(keyOf(connection),connection.transport)}closed(connection){let key=keyOf(connection);this.attached.delete(key)&&this.writer.status.publish(this.handle,"detach","client"),this.writer.unregisterConnection(key)}attach(connection){let key=keyOf(connection);return this.attached.has(key)?!1:(this.attached.add(key),this.writer.attachConnectionToSession(key,this.handle),this.writer.status.publish(this.handle,"attach","client"),!0)}isAttached(connection){return this.attached.has(keyOf(connection))}run(connection,task){return this.writer.withConnection(keyOf(connection),task)}respond(connection,answer2){this.writer.enqueueControl(answer2,keyOf(connection)).catch(()=>connection.transport.close?.())}dispose(){this.stopRecords()}entryView(){let manager=this.session.sessionManager,path=this.session.sessionFile,name=manager.getSessionName();return{state:"open",kind:"interactive",cwd:manager.getCwd(),attachments:1+this.attached.size,durableSessionId:this.session.sessionId,...path!==void 0?{sessionPath:path}:{},...name!==void 0?{name}:{},context:{}}}},NULL_CONNECTION="tui-null";function keyOf(connection){return`tui-${connection.id}`}import{randomUUID}from"node:crypto";import{realpathSync}from"node:fs";import{resolve}from"node:path";var TUI_RPC_COMMANDS=["open_session","subscribe_sessions","unsubscribe_sessions","steer","follow_up","prompt","get_effect_status"];async function runTuiRpcCommand(context,connection,command){switch(command.type){case"open_session":return openSession(context,connection,command);case"subscribe_sessions":return subscribe(context,connection,command);case"unsubscribe_sessions":return answerUnsubscribeSessions(command,keyOf(connection),context.attachments.writer.status);case"steer":case"follow_up":return admitInput(context,command,command.type==="steer"?"steer":"followUp",command.whenIdle);case"prompt":return admitPrompt(context,command);case"get_effect_status":return runGetEffectStatus({session:context.session,by:{connectionId:keyOf(connection)},sessionId:context.attachments.handle},command);default:return}}function idOf(command){return typeof command.id=="string"?command.id:void 0}function openSession(context,connection,command){let{session,attachments}=context,ownPath=typeof command.sessionPath=="string"&&samePath(command.sessionPath,session.sessionFile),ownId=command.sessionId!==void 0&&command.sessionId===session.sessionId;return!ownPath&&!ownId?refusal(idOf(command),"open_session","terminal_single_session",{reason:"this terminal hosts one session and the request names another",action:"open it by this terminal's sessionPath, or open the other session on a host"}):(attachments.run(connection,()=>{attachments.attach(connection),attachments.writer.enqueue(attachments.handle,{id:command.id,type:"response",command:"open_session",success:!0,data:{sessionId:attachments.handle,state:buildRpcSessionState(session),attached:!0}})}),null)}function subscribe(context,connection,command){let{writer}=context.attachments,key=keyOf(connection),{answer:answer2,activate}=answerSubscribeSessions(command,key,writer.status);return activate===void 0?answer2:(writer.enqueueControl(answer2,key).then(()=>{writer.hasConnection(key)?writer.status.activate(activate):writer.status.unsubscribe(key,activate)}).catch(()=>writer.status.unsubscribe(key,activate)),null)}function admitPrompt(context,command){let behavior=command.streamingBehavior;return behavior===void 0&&context.session.isStreaming?refusal(idOf(command),"prompt","session_busy",{reason:"a turn is running and the prompt names no streamingBehavior",action:'send it with streamingBehavior "steer" or "followUp", or as a steer/follow_up'}):admitInput(context,command,behavior==="followUp"?"followUp":"steer","start")}var UNSERVED_INPUT_FIELDS=["images","thinkingLevel","expandPromptTemplates","unknownCommandAsText","sessionTitlePrompt","enqueueOrder"];function samePath(requested,own){if(own===void 0)return!1;let canonical=path=>{try{return realpathSync(resolve(path))}catch{return resolve(path)}};return canonical(requested)===canonical(own)}function admitInput(context,command,deliverAs,whenIdle){let id=idOf(command),unserved=UNSERVED_INPUT_FIELDS.filter(field=>command[field]!==void 0);if(unserved.length>0)return refusal(id,command.type,"unsupported_field",{reason:`a terminal delivers input through its admission, which carries text only, not ${unserved.join(", ")}`,action:"send the message without those fields, or send it to a host session"});let message=command.message;if(typeof message!="string"||message.trim()==="")return refusal(id,command.type,"invalid_message",{reason:"message is empty",action:"send a non-empty message"});if(whenIdle!==void 0&&whenIdle!=="queue"&&whenIdle!=="start")return refusal(id,command.type,"invalid_when_idle",{reason:`whenIdle must be "queue" or "start", not ${JSON.stringify(whenIdle)}`,action:'send whenIdle: "queue" (the default) or "start"'});let admission=context.session.externalAdmission,clientMessageId=typeof command.clientMessageId=="string"?command.clientMessageId:void 0,expected=typeof command.expected_turn_id=="number"?command.expected_turn_id:admission.turnEpoch,result=admission.admit({delivery_id:clientMessageId??`tui-rpc-${randomUUID()}`,text:message,sender:{kind:"external",platform:"rpc"},deliverAs,expected_turn_id:expected,whenIdle:whenIdle==="start"?"start":"queue"}),identity=clientMessageId===void 0?{}:{clientMessageId};switch(result.kind){case"started":return answered(id,command.type,{disposition:"started",...identity});case"steered":case"queued":return answered(id,command.type,{disposition:"queued",...identity});case"already_admitted":return answered(id,command.type,{disposition:"queued",duplicate:!0,...identity});case"held_draft":return refusal(id,command.type,"held_draft",{reason:"the user is composing in this terminal, so nothing was delivered",action:"retry after the draft is sent or cleared"});case"turn_conflict":return refusal(id,command.type,"turn_conflict",{reason:`the turn moved on (now ${result.turn_epoch}); this steer named an earlier one`,action:"read get_state's turn_epoch and send it again"})}}function answered(id,command,data){return{...id===void 0?{}:{id},type:"response",command,success:!0,data}}import{chmod}from"node:fs/promises";import{createServer}from"node:net";async function listenControlSocket(socketPath,secret,handlers){let clients=new Set,nextConnection=0,server=createServer(socket=>{clients.add(socket),socket.once("close",()=>clients.delete(socket)),socket.on("error",()=>socket.destroy()),authenticateSocket(socket,secret,()=>acceptConnection(socket,++nextConnection,handlers))});return await new Promise((resolve2,reject)=>{server.once("error",reject),server.listen(socketPath,()=>{server.off("error",reject),resolve2()})}),server.on("error",error=>handlers.listenerError(error)),await chmod(socketPath,384),{close:()=>closeServer(server,clients)}}function acceptConnection(socket,id,handlers){let connection={id,send:record=>{handlers.respond!==void 0?handlers.respond(connection,record):socket.destroyed||socket.write(serializeJsonLine(record))},transport:socketSink(socket)};handlers.opened?.(connection);let detach=attachJsonlLineReader(socket,line=>{answer(connection,line,handlers)},{maxLineLength:MAX_RPC_LINE_CHARACTERS,onOversizedLine:()=>connection.send(failure(void 0,"parse","RPC line exceeds the size limit."))});socket.once("close",()=>{detach(),handlers.closed(connection)})}async function answer(connection,line,handlers){let parsed;try{parsed=JSON.parse(line)}catch{connection.send(failure(void 0,"parse","Invalid JSON."));return}let shapeError=rpcCommandShapeError(parsed);if(shapeError!==void 0||!isCommand(parsed)){connection.send(failure(void 0,"parse",shapeError??"RPC command needs a string `type`."));return}let answer2=await handlers.command(connection,parsed);answer2!==null&&connection.send(answer2)}function isCommand(value){return typeof value=="object"&&value!==null&&"type"in value&&typeof value.type=="string"}function failure(id,command,error){return{...id===void 0?{}:{id},type:"response",command,success:!1,error}}function success(id,command,data){return{...id===void 0?{}:{id},type:"response",command,success:!0,...data===void 0?{}:{data}}}function closeServer(server,clients){for(let client of clients)client.destroy();return new Promise(resolve2=>server.close(()=>resolve2()))}var SESSION_CONTROL_COMMANDS=["get_available_models","get_available_thinking_levels","set_model","set_thinking_level","interrupt"];async function runSessionControlCommand(session,controls,command){let{id,type}=command;switch(type){case"get_available_models":return success(id,type,await availableModelsData(session));case"get_available_thinking_levels":return success(id,type,{levels:session.getAvailableThinkingLevels()});case"set_model":return await setModel(session,controls,command);case"set_thinking_level":{let level=session.getAvailableThinkingLevels().find(candidate=>candidate===command.level);return level===void 0?failure(id,type,unsupportedThinkingLevel(command.level)):(controls.selectThinkingLevel(level,command.scope!=="turn"),success(id,type))}case"interrupt":return success(id,type,await interruptRunningTurn(session,command.turnId,()=>controls.interruptTurn()));default:return}}async function setModel(session,controls,command){let{id,type}=command,model=(await session.modelRegistry.getAvailable()).find(candidate=>candidate.provider===command.provider&&candidate.id===command.modelId);if(model===void 0)return failure(id,type,`Model not found: ${String(command.provider)}/${String(command.modelId)}`);try{let change=await controls.selectModel(model);return success(id,type,{...model,systemPromptName:change?.systemPromptName})}catch(error){return failure(id,type,error instanceof Error?error.message:String(error))}}var TUI_CONTROL_CAPABILITY="tui_control",TUI_CONTROL_COMMANDS=["get_protocol_info","list_sessions","get_state","get_messages","set_session_name","subscribe","wake","extension_ui_response",...SESSION_CONTROL_COMMANDS,...TUI_RPC_COMMANDS];async function runControlCommand(context,connection,command){let{id,type}=command,{session}=context;switch(type){case"get_protocol_info":{let build=engineBuildIdentity();return success(id,type,{protocolVersion:1,serverVersion:VERSION,capabilities:[TUI_CONTROL_CAPABILITY,SESSION_STATUS_CAPABILITY],mode:"tui",endpoint_kind:"tui",instanceId:context.instanceId,generation:0,engineVersion:build.text,engineOrdinal:build.ordinal,commands:TUI_CONTROL_COMMANDS})}case"list_sessions":return success(id,type,{sessions:[sessionRow(session)]});case"get_state":return success(id,type,{...buildRpcSessionState(session),turn_epoch:session.externalAdmission.turnEpoch,blocking_question:context.surface.blockingQuestion(),compacting:session.isCompacting,editor_has_draft:context.surface.draftHold()!==void 0,state_version:context.feed.stateVersion});case"get_messages":return success(id,type,{messages:session.messages});case"set_session_name":{let name=typeof command.name=="string"?command.name.trim():"";return name===""?failure(id,type,"Session name cannot be empty"):(session.setSessionName(name),success(id,type))}case"subscribe":{let cursor=typeof command.cursor=="number"?command.cursor:void 0;return success(id,type,{cursor:context.feed.subscribe(connection.id,cursor,connection.send)})}case"wake":{let ids=Array.isArray(command.delivery_ids)?command.delivery_ids.filter(entry=>typeof entry=="string"):void 0,result=await context.wake(ids);return success(id,type,{admitted:result.admitted??[]})}case"extension_ui_response":return answerQuestion(context.surface,command);default:{let rpc=await runTuiRpcCommand(context,connection,command);return rpc!==void 0?rpc:await runSessionControlCommand(session,context.surface,command)??failure(id,type,"unsupported")}}}function sessionRow(session){let manager=session.sessionManager,created=manager.getHeader()?.timestamp??null,last=manager.getEntries().at(-1);return{sessionId:session.sessionId,sessionPath:session.sessionFile??null,session_file:session.sessionFile??null,kind:"interactive",surface:"tui",cwd:manager.getCwd(),name:session.sessionName??null,created_at:created,updated_at:last?.timestamp??created,attachments:1}}function answerQuestion(surface,command){let frameId=command.id,requestId=answeredUiRequestId(command),request=requestId===void 0?void 0:surface.pendingQuestion(requestId);if(requestId===void 0||request===void 0)return failure(frameId,"extension_ui_response","unknown_request");let response=questionResponse(command,request.questions);return response==="question_incomplete"?failure(frameId,"extension_ui_response",response):response===void 0||!surface.answerQuestion(requestId,response)?failure(frameId,"extension_ui_response","invalid_response"):success(frameId,"extension_ui_response")}function questionResponse(command,questions){if(command.cancelled===!0)return{status:"cancelled",cancelOrigin:"user",answers:{},unanswered:[]};let answers=command.answers;if(typeof answers!="object"||answers===null||Array.isArray(answers))return;let parsed={};for(let[question,value]of Object.entries(answers)){if(typeof value!="object"||value===null||!("selected"in value)||!Array.isArray(value.selected))return;let selected=value.selected.filter(entry=>typeof entry=="string"),text="text"in value&&typeof value.text=="string"?value.text:void 0;parsed[question]=text===void 0?{selected}:{selected,text}}let comment=typeof command.comment=="string"?command.comment:void 0,status=settledQuestionStatus(parsed,comment);if(status===void 0)return"question_incomplete";let unanswered=unansweredQuestionIds(questions,parsed);return{status,resolvedBy:"control_endpoint",answers:parsed,unanswered,...comment===void 0?{}:{comment}}}var ControlFeed=class{constructor(){this.seq=0,this.stateVersionValue=0,this.ring=[],this.subscribers=new Map}get stateVersion(){return this.stateVersionValue}publish(kind,data={}){kind==="state"&&(this.stateVersionValue+=1);let event={type:"session_control_event",seq:++this.seq,kind,data:kind==="state"?{...data,state_version:this.stateVersionValue}:data};this.ring.push(event),this.ring.length>256&&this.ring.shift();for(let send of this.subscribers.values())send(event)}subscribe(connection,cursor,send){if(this.subscribers.set(connection,send),cursor!==void 0)for(let event of this.ring)event.seq>cursor&&send(event);return this.seq}unsubscribe(connection){this.subscribers.delete(connection)}clear(){this.subscribers.clear()}};import{createHash}from"node:crypto";import{rmSync}from"node:fs";import{chmod as chmod2,lstat,mkdir,realpath,rm}from"node:fs/promises";import{tmpdir}from"node:os";import{dirname,join}from"node:path";var PRIVATE_DIRECTORY_MODE=448,REGISTRY_LOCK_WAIT_MS=5e3;async function resolveTuiSocket(agentDir,instanceId){let name=tuiSocketName(instanceId),primary=join(agentDir,"rpc","tui",name);if(Buffer.byteLength(primary)<=MAX_SOCKET_PATH_BYTES)return await makePrivateDirectory(dirname(primary)),primary;let fallbackName=`senpi-rpc-${createHash("sha256").update(agentDir).digest("hex").slice(0,8)}`,scopedRoot=join(tmpdir(),fallbackName),root=Buffer.byteLength(join(scopedRoot,"tui",name))<=MAX_SOCKET_PATH_BYTES?scopedRoot:join("/tmp",fallbackName),tuiRoot=join(root,"tui");await makePrivateDirectory(tuiRoot);for(let directory of[root,tuiRoot])await assertPrivateDirectory(directory);let fallback=join(tuiRoot,name);if(Buffer.byteLength(fallback)>MAX_SOCKET_PATH_BYTES)throw new Error(`socket path ${fallback} exceeds ${MAX_SOCKET_PATH_BYTES} bytes`);return fallback}async function makePrivateDirectory(directory){await mkdir(directory,{recursive:!0,mode:PRIVATE_DIRECTORY_MODE}),await chmod2(directory,PRIVATE_DIRECTORY_MODE)}async function assertPrivateDirectory(directory){let stat=await lstat(await realpath(directory)),ownedByUs=process.getuid===void 0||stat.uid===process.getuid();if(!stat.isDirectory()||!ownedByUs||(stat.mode&63)!==0)throw new Error(`alt_root_unsafe: ${directory} is not a private directory of this user`)}async function registerTuiEndpoint(options){let paths=createHostDaemonPaths({socket:options.socket,agentDir:options.agentDir}),release=await acquireHostEnsureLock(options.socket,REGISTRY_LOCK_WAIT_MS);try{await writeHostRegistration(paths,{record:{pid:process.pid,processStartTime:await thisProcessStartTime()},socket:options.socket,instanceId:options.instanceId,generation:0,launchProfileId:"tui",build:engineBuildIdentity()},{fresh:!0}),await createDaemonDirectories(paths,{kind:"tui"})}finally{await release()}return{paths,socket:options.socket}}async function unregisterTuiEndpoint(entry){let release=await acquireHostEnsureLock(entry.socket,REGISTRY_LOCK_WAIT_MS).catch(()=>{});try{await rm(entry.socket,{force:!0}),await rm(socketSecretPath(entry.socket),{force:!0}),await rm(entry.paths.dir,{recursive:!0,force:!0})}finally{await release?.()}}function unregisterTuiEndpointSync(entry){rmSync(entry.socket,{force:!0}),rmSync(socketSecretPath(entry.socket),{force:!0}),rmSync(entry.paths.dir,{recursive:!0,force:!0})}var REPORT_TEXT_LIMIT=4e3;function activateControlEndpoint(parts){let{context,feed,wake}=parts,{session,surface}=context;session.externalAdmission.setEditorSource(()=>editorHold(context));let unsubscribeSession=session.subscribe(event=>{event.type==="agent_start"?feed.publish("state"):event.type==="agent_idle"?(feed.publish("completion",{turn_epoch:session.externalAdmission.turnEpoch}),feed.publish("state"),wake("idle")):event.type==="agent_end"||event.type==="queue_update"||event.type==="compaction_start"||event.type==="compaction_end"?feed.publish("state"):event.type==="message_end"&&event.message.role==="assistant"&&feed.publish("report",{text:assistantText(event.message).slice(0,REPORT_TEXT_LIMIT)})}),unsubscribeEmitted=session.externalAdmission.onEmitted(()=>{wake("emitted")}),unsubscribeInputs=session.externalAdmission.onInputsSettled(()=>queueMicrotask(()=>{wake("submission")})),stopContinue=onProcessContinue(()=>{wake("continue")}),exitCleanup=()=>unregisterTuiEndpointSync(parts.entry);process.once("exit",exitCleanup);let disposing,dispose=()=>(disposing??=(async()=>{process.removeListener("exit",exitCleanup),unsubscribeSession(),unsubscribeEmitted(),unsubscribeInputs(),stopContinue(),parts.stopInbox(),parts.scheduler.dispose(),feed.clear(),session.externalAdmission.setEditorSource(void 0),await parts.server.close(),await sessionReferenced(parts.options,surface)||await session.sessionManager.discardHeaderOnlyFile(),await unregisterTuiEndpoint(parts.entry)})(),disposing);return{socket:parts.entry.socket,wake:reason=>{wake(reason)},noteState:()=>feed.publish("state"),noteQuestions:()=>feed.publish("question",{pending:[...surface.pendingQuestionIds()]}),dispose}}function editorHold(context){let hold=context.surface.draftHold(),revision=context.editorRevision();return hold===void 0?{revision}:{hold_reason:hold,revision}}async function sessionReferenced(options,surface){if(options.isSessionReferenced===void 0)return!1;try{return await options.isSessionReferenced()}catch(error){return surface.notice(`control endpoint kept the session file: ${error instanceof Error?error.message:String(error)}`),!0}}function assistantText(message){return message.role!=="assistant"?"":message.content.flatMap(part=>part.type==="text"?[part.text]:[]).join(`
3
- `)}async function registerSessionControlEndpoint(context,options){let cleanups=[];try{let endpoint=await openEndpoint(context,options,cleanups);return{registration:{status:"registered",socket:endpoint.socket,dispose:endpoint.dispose},endpoint}}catch(error){for(let cleanup of cleanups.reverse())await Promise.resolve(cleanup()).catch(()=>{});let reason=errorText(error);return context.surface.notice(`control endpoint unavailable: ${reason}`),{registration:{status:"failed",reason}}}}async function openEndpoint(context,options,cleanups){let{session,agentDir,surface}=context;thisProcessStartTime();let headerDurable=session.sessionManager.persistHeaderNow();headerDurable.catch(()=>{});let instanceId=randomUUID2(),socket=await resolveTuiSocket(agentDir,instanceId);cleanups.push(()=>rm2(socket,{force:!0}),()=>rm2(socketSecretPath(socket),{force:!0}));let secret=await createSocketSecret(socketSecretPath(socket)),feed=new ControlFeed,failing,scheduler=new WakeScheduler(async event=>{await session.extensionRunner.emit(event);let result=await options.drain(event)??{admitted:[]};return failing=void 0,result},error=>{let reason=errorText(error);reason!==failing&&(failing=reason,surface.notice(`control endpoint drain failed: ${reason}`))});cleanups.push(()=>scheduler.dispose());let wake=(reason,ids)=>scheduler.request(reason,ids),attachments=new ControlAttachments(session,()=>surface.pendingQuestionIds().length);cleanups.push(()=>attachments.dispose());let commandContext={instanceId,session,surface,feed,wake:ids=>wake("command",ids),attachments},server=await listenControlSocket(socket,secret,{command:(connection,command)=>runControlCommand(commandContext,connection,command),opened:connection=>attachments.opened(connection),respond:(connection,answer2)=>attachments.respond(connection,answer2),closed:connection=>{feed.unsubscribe(connection.id),attachments.closed(connection)},listenerError:error=>surface.notice(`control endpoint listener failed: ${error.message}`)});cleanups.push(()=>server.close()),await headerDurable;let entry=await registerTuiEndpoint({agentDir,socket,instanceId});cleanups.push(()=>unregisterTuiEndpoint(entry));let inbox=await watchInbox(options.inboxDir,()=>{wake("inbox")},error=>surface.notice(`control endpoint inbox watch failed: ${errorText(error)}`));cleanups.push(()=>inbox.stop());let endpoint=activateControlEndpoint({context,options,entry,server,scheduler,feed,stopInbox:inbox.stop,wake});return endpoint.wake("inbox"),inbox.armed.then(()=>endpoint.wake("inbox")),setImmediate(()=>{gcHostEndpoints(agentDir,{kinds:["tui"]}).catch(error=>surface.notice(`control endpoint gc of dead terminals failed: ${errorText(error)}`))}),endpoint}function errorText(error){return error instanceof Error?error.message:String(error)}export{registerSessionControlEndpoint};
@@ -1,2 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{SessionSelectorComponent,createStartupTui,startStartupTui}from"./chunk-FFQOEC76.js";import{KeybindingsManager}from"./chunk-GXY5JEI5.js";import"./chunk-EHQXLHRB.js";import"./chunk-XF3LJC3O.js";import"./chunk-CNPDUC4D.js";import"./chunk-MLVIYDHK.js";import"./chunk-QMRJYMNH.js";import"./chunk-MSQCTH6V.js";import"./chunk-KLAX467B.js";import"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import"./chunk-SOMFLLPD.js";import"./chunk-26UBFF6N.js";import"./chunk-U3VOXCGP.js";import"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-PELNNWGO.js";import{setKeybindings}from"./chunk-FDL4CF6F.js";import"./chunk-YU4AYH4C.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-YU2P3CAR.js";import"./chunk-ZOFZRJSL.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";async function selectSession(currentSessionsLoader,allSessionsLoader,settingsManager){let ui=await createStartupTui(settingsManager);return new Promise(resolve=>{let keybindings=KeybindingsManager.create();setKeybindings(keybindings);let resolved=!1,selector=new SessionSelectorComponent(currentSessionsLoader,allSessionsLoader,path=>{resolved||(resolved=!0,ui.stop(),resolve(path))},()=>{resolved||(resolved=!0,ui.stop(),resolve(null))},()=>{ui.stop(),process.exit(0)},()=>ui.requestRender(),{showRenameHint:!1,keybindings});ui.addChild(selector),ui.setFocus(selector.getSessionList()),startStartupTui(ui,settingsManager)})}export{selectSession};