@code-yeongyu/senpi 2026.11.13 → 2026.11.15

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 (95) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/bundle/chunks/{args-H56W53X6.js → args-JWBI5LNO.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-MNN2TINI.js → azure-openai-responses-PEMLRPJ5.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-HZQHA4PA.js → chunk-3RILB2OD.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-Y4PFEXFN.js → chunk-5IXYN6DK.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-BKDXY6EM.js → chunk-5NECOJNK.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-NI2AOYP6.js → chunk-6MRUNB3Z.js} +1 -1
  8. package/dist/bundle/chunks/chunk-6QQL3SKM.js +2 -0
  9. package/dist/bundle/chunks/{chunk-I4N2OIY4.js → chunk-6QXAYNO7.js} +17 -17
  10. package/dist/bundle/chunks/{chunk-7T2LAWZ4.js → chunk-73HGQTJN.js} +1 -1
  11. package/dist/bundle/chunks/chunk-75O3CWR5.js +2 -0
  12. package/dist/bundle/chunks/{chunk-AZ27TE3H.js → chunk-7BX3JQ7F.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-NDI6N4NJ.js → chunk-7CXLNKEH.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-E6ZBTSC6.js → chunk-A3LGSX7Z.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-7GD2EO6T.js → chunk-FYVQEZYN.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-U4FAWC6C.js → chunk-GXPH7RN6.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-SFACYIB6.js → chunk-IK3S2NDB.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-V4VDIV3U.js → chunk-PWA75RQU.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-IREUIMFE.js → chunk-PWTXZXHH.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-KKB3K5CV.js → chunk-Q4RJ4WLE.js} +1 -1
  21. package/dist/bundle/chunks/chunk-QVG5SUSV.js +2 -0
  22. package/dist/bundle/chunks/chunk-RLIY3AUC.js +2 -0
  23. package/dist/bundle/chunks/{chunk-EQT4WNCW.js → chunk-TACOXP5H.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-NXGSYUMV.js → chunk-TB6LIKVR.js} +2 -2
  25. package/dist/bundle/chunks/{chunk-JLCZIEBC.js → chunk-THYIV26N.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-6FE42M54.js → chunk-VGHGM5PR.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-CU6HUYL7.js → chunk-WAGFTIT4.js} +1 -1
  28. package/dist/bundle/chunks/{chunk-UYPH6RHY.js → chunk-Z4PN2MDA.js} +2 -2
  29. package/dist/bundle/chunks/{chunk-JJYN347Z.js → chunk-ZJUL5ODW.js} +1 -1
  30. package/dist/bundle/chunks/{cli-main-MY53RXU3.js → cli-main-MM2XCVYE.js} +1 -1
  31. package/dist/bundle/chunks/credential-accounts-RXZIUKFM.js +2 -0
  32. package/dist/bundle/chunks/github-copilot.js +1 -1
  33. package/dist/bundle/chunks/{hand-entry-AXTVMVJK.js → hand-entry-MBOPYO6I.js} +1 -1
  34. package/dist/bundle/chunks/{headless-host-SU5O2KZ2.js → headless-host-OEK6W65T.js} +1 -1
  35. package/dist/bundle/chunks/{health-write-TN7EXGLI.js → health-write-44JERGEJ.js} +1 -1
  36. package/dist/bundle/chunks/{help-fast-path-TFQ4HJNO.js → help-fast-path-JWHUCE4E.js} +1 -1
  37. package/dist/bundle/chunks/{host-command-FG56Y53E.js → host-command-O2K2WIPO.js} +1 -1
  38. package/dist/bundle/chunks/{host-session-command-UFEOW7EP.js → host-session-command-EWA6N4JJ.js} +1 -1
  39. package/dist/bundle/chunks/interactive-mode-VSZYRVYY.js +2 -0
  40. package/dist/bundle/chunks/{login-health-XBTIORM4.js → login-health-V4B6LSCP.js} +1 -1
  41. package/dist/bundle/chunks/main-VEWKRBTD.js +2 -0
  42. package/dist/bundle/chunks/{multi-session-host-Q6SHI22A.js → multi-session-host-HC6NR5N2.js} +1 -1
  43. package/dist/bundle/chunks/{openai-codex-responses-VRGOAFEG.js → openai-codex-responses-IFPWK7NG.js} +1 -1
  44. package/dist/bundle/chunks/openai-responses-2BTL5MA2.js +5 -0
  45. package/dist/bundle/chunks/{package-manager-cli-LILAWI3Q.js → package-manager-cli-OZ6DK6GI.js} +3 -3
  46. package/dist/bundle/chunks/{role-KODRTWH5.js → role-BTH5PVME.js} +1 -1
  47. package/dist/bundle/chunks/{rotation-stream-2KNROTYB.js → rotation-stream-ZGPXLY62.js} +1 -1
  48. package/dist/bundle/chunks/rpc-mode-WPF3NVBL.js +2 -0
  49. package/dist/bundle/chunks/{run-attached-tui-OEFHV5CZ.js → run-attached-tui-RVVYEINN.js} +1 -1
  50. package/dist/bundle/chunks/{schedule-command-VO4RP2KX.js → schedule-command-6TAAG2KU.js} +1 -1
  51. package/dist/bundle/chunks/{session-control-endpoint-CCVRJHSC.js → session-control-endpoint-3FNVOKKT.js} +1 -1
  52. package/dist/bundle/chunks/{session-picker-VN5I2ZDI.js → session-picker-YDXDCBRL.js} +1 -1
  53. package/dist/bundle/chunks/session-slot-N4E4OSCX.js +2 -0
  54. package/dist/bundle/chunks/session-worker.js +22 -21
  55. package/dist/bundle/chunks/{state-store-7RVODZJU.js → state-store-I6MUHET3.js} +1 -1
  56. package/dist/bundle/cli.js +2 -2
  57. package/dist/bundle/index.js +1 -1
  58. package/dist/bundle/rpc-entry.js +1 -1
  59. package/dist/bundle/runtime-manifest.json +1 -1
  60. package/dist/core/agent-session.d.ts +5 -3
  61. package/dist/core/agent-session.js +16 -6
  62. package/dist/core/credential-accounts.d.ts +5 -3
  63. package/dist/core/credential-accounts.js +8 -6
  64. package/dist/core/credential-pool/classify.js +5 -1
  65. package/dist/core/extensions/builtin/anthropic-subscription/content-blocks.d.ts +6 -0
  66. package/dist/core/extensions/builtin/anthropic-subscription/content-blocks.js +14 -0
  67. package/dist/core/extensions/builtin/anthropic-subscription/prompt-bridge.js +3 -1
  68. package/dist/core/extensions/builtin/anthropic-subscription/session-sync.js +4 -1
  69. package/dist/core/extensions/builtin/permission-system/index.js +5 -1
  70. package/dist/core/reasoning-baseline.d.ts +8 -1
  71. package/dist/core/reasoning-baseline.js +24 -0
  72. package/dist/modes/rpc/connection-handler.js +4 -0
  73. package/dist/modes/rpc/method-classes-schema-session.d.ts +3 -0
  74. package/dist/modes/rpc/method-classes-schema-session.js +6 -2
  75. package/dist/modes/rpc/method-classes-schema.d.ts +3 -0
  76. package/dist/modes/rpc/project-expected-cwd.d.ts +29 -0
  77. package/dist/modes/rpc/project-expected-cwd.js +45 -0
  78. package/dist/modes/rpc/rpc-error-types.d.ts +7 -1
  79. package/dist/modes/rpc/rpc-error-types.js +6 -0
  80. package/dist/modes/rpc/rpc-session-command-types.d.ts +3 -0
  81. package/dist/package-manager-cli.d.ts +14 -0
  82. package/dist/package-manager-cli.js +20 -4
  83. package/dist/utils/version-check.d.ts +10 -7
  84. package/dist/utils/version-check.js +24 -5
  85. package/docs/rpc.md +20 -7
  86. package/package.json +7 -7
  87. package/dist/bundle/chunks/chunk-GLTOBXZY.js +0 -2
  88. package/dist/bundle/chunks/chunk-PBUV2Z3R.js +0 -2
  89. package/dist/bundle/chunks/chunk-WRBOKYPS.js +0 -2
  90. package/dist/bundle/chunks/credential-accounts-ZB5IXHIG.js +0 -2
  91. package/dist/bundle/chunks/interactive-mode-PHES47E3.js +0 -2
  92. package/dist/bundle/chunks/main-PR4FI6HQ.js +0 -2
  93. package/dist/bundle/chunks/openai-responses-I7PXRWCM.js +0 -4
  94. package/dist/bundle/chunks/rpc-mode-CGVK4SSA.js +0 -2
  95. package/dist/bundle/chunks/session-slot-GHJVOSG7.js +0 -2
@@ -1,2 +1,2 @@
1
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{attemptCandidates,noSlotsError,orderAccounts,preferHeadroom,rendezvousOrder}from"./chunk-PBUV2Z3R.js";var headroomAffinities=new WeakMap;function rememberedHeadroomAccount(repository,providerId,affinityKey){return headroomAffinities.get(repository)?.get(`${providerId}\0${affinityKey}`)}function rememberHeadroomAccount(repository,providerId,affinityKey,account){let sessions=headroomAffinities.get(repository)??new Map;sessions.set(`${providerId}\0${affinityKey}`,account),headroomAffinities.set(repository,sessions)}function orderRotationSlots(candidates,policy){let ranked=policy.useAffinity?rendezvousOrder(policy.affinityKey,candidates,policy.hasher):candidates;return orderAccounts(candidates,ranked,policy.order,policy.strategy,policy.roundRobinOffset)}function pickRotationSlot(candidates,policy){let pinned=candidates.find(candidate=>candidate.pinned===!0);if(pinned)return pinned;let ordered=orderRotationSlots(candidates,policy),headroom=policy.headroom;return headroom?preferHeadroom(ordered,headroom.providerId,headroom.limits,headroom.now,headroom.remembered)[0]:ordered[0]}function selectSessionSlot(slots,policy,now){if(slots.length===0)return;let candidates=attemptCandidates(slots,new Set,now);if(candidates.length===0)throw noSlotsError(slots,now);return pickRotationSlot(candidates,policy)}export{rememberedHeadroomAccount,rememberHeadroomAccount,orderRotationSlots,pickRotationSlot,selectSessionSlot};
2
+ import{attemptCandidates,noSlotsError,orderAccounts,preferHeadroom,rendezvousOrder}from"./chunk-RLIY3AUC.js";var headroomAffinities=new WeakMap;function rememberedHeadroomAccount(repository,providerId,affinityKey){return headroomAffinities.get(repository)?.get(`${providerId}\0${affinityKey}`)}function rememberHeadroomAccount(repository,providerId,affinityKey,account){let sessions=headroomAffinities.get(repository)??new Map;sessions.set(`${providerId}\0${affinityKey}`,account),headroomAffinities.set(repository,sessions)}function orderRotationSlots(candidates,policy){let ranked=policy.useAffinity?rendezvousOrder(policy.affinityKey,candidates,policy.hasher):candidates;return orderAccounts(candidates,ranked,policy.order,policy.strategy,policy.roundRobinOffset)}function pickRotationSlot(candidates,policy){let pinned=candidates.find(candidate=>candidate.pinned===!0);if(pinned)return pinned;let ordered=orderRotationSlots(candidates,policy),headroom=policy.headroom;return headroom?preferHeadroom(ordered,headroom.providerId,headroom.limits,headroom.now,headroom.remembered)[0]:ordered[0]}function selectSessionSlot(slots,policy,now){if(slots.length===0)return;let candidates=attemptCandidates(slots,new Set,now);if(candidates.length===0)throw noSlotsError(slots,now);return pickRotationSlot(candidates,policy)}export{rememberedHeadroomAccount,rememberHeadroomAccount,orderRotationSlots,pickRotationSlot,selectSessionSlot};
@@ -0,0 +1,2 @@
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{external_exports}from"./chunk-36BLGKRO.js";var clientMessageIdentitySchema=external_exports.object({clientMessageId:external_exports.string().min(1).max(256).optional(),clientTurnId:external_exports.string().min(1).max(256).optional()});function clientMessageIdentity(value={}){return{...value.clientMessageId===void 0?{}:{clientMessageId:value.clientMessageId},...value.clientTurnId===void 0?{}:{clientTurnId:value.clientTurnId}}}function readClientMessageIdentity(value){let parsed=clientMessageIdentitySchema.safeParse(value);return parsed.success?clientMessageIdentity(parsed.data):{}}var RPC_ERROR_UNKNOWN_SESSION="unknown_session",RPC_ERROR_SESSION_NOT_ATTACHED="session_not_attached";var RPC_ERROR_SESSION_CLOSING="session_closing";var RPC_ERROR_SESSION_HELD="session_held";var RPC_ERROR_MISSING_SESSION_ID="missing_session_id";var RPC_ERROR_INVALID_PATH="invalid_path",RPC_ERROR_INVALID_ARGUMENT="invalid_argument",RPC_ERROR_RESPONSE_TOO_LARGE="response_too_large",RPC_ERROR_RESPONSE_UNWRITABLE="response_unwritable",RPC_ERROR_PROJECT_CWD_MISMATCH="project_cwd_mismatch",RPC_ERROR_OPEN_FAILED="open_failed",RPC_ERROR_OWNER_CHANGED="owner_changed";var RPC_ERROR_MEDIA_NOT_FOUND="media_not_found",RPC_ERROR_PROJECT_TRUST_LOCKED="project_trust_locked",RPC_ERROR_PROJECT_TRUST_EXTENSION_DECIDED="project_trust_extension_decided",RPC_ERROR_PROJECT_SETTINGS_WRITE_FAILED="project_settings_write_failed",RPC_ERROR_PROJECT_NOT_TRUSTED="project_not_trusted",RPC_ERROR_PROJECT_SETTINGS_UNREADABLE="project_settings_unreadable",RPC_ERROR_PROJECT_FILE_NOT_ALLOWED="project_file_not_allowed",RPC_ERROR_PROJECT_FILE_CONFLICT="project_file_conflict",RPC_ERROR_PROJECT_FILE_TOO_LARGE="project_file_too_large",RPC_ERROR_PROJECT_FILE_WRITE_FAILED="project_file_write_failed",RPC_ERROR_INVALID_SESSION_CONTEXT="invalid_session_context",RPC_ERROR_INVALID_SESSION_ENV="invalid_session_env",RPC_ERROR_INVALID_SUBSCRIPTION="invalid_subscription",RPC_ERROR_UNKNOWN_SUBSCRIPTION="unknown_subscription",RPC_ERROR_SUBSCRIPTION_LIMIT="subscription_limit",RPC_ERROR_UNSUPPORTED_TRANSPORT="unsupported_transport",RPC_ERROR_FEATURE_DISABLED="feature_disabled",RPC_ERROR_INVALID_SESSION_KIND="invalid_session_kind",RPC_ERROR_INVALID_LAUNCH_PROFILE="invalid_launch_profile";var RPC_ERROR_WARM_FAILED="warm_failed";var RPC_ERROR_ENTRY_NOT_FOUND="not_found",RPC_ERROR_MODEL_NOT_FOUND="model_not_found",RPC_ERROR_EFFECT_ID_CONFLICT="effect_id_conflict",RPC_ERROR_TRANSCRIPT_UNREADABLE="transcript_unreadable",RPC_ERROR_PROVIDER_UNAVAILABLE="provider_unavailable",RPC_ERROR_PROVIDER_CREDENTIALS_MISSING="provider_credentials_missing",RPC_ERROR_PROVIDER_CREDENTIALS_EXPIRED="provider_credentials_expired",RPC_ERROR_NO_MODEL_SELECTED="no_model_selected",RPC_ERROR_TURN_CONFLICT="turn_conflict",RPC_ERROR_CONTEXT_BUDGET="context_budget",RPC_ERROR_EVAL_CELL_NOT_FOUND="eval_cell_not_found",RPC_ERROR_INVALID_EVAL_CELL_REQUEST="invalid_eval_cell_request",RPC_ERROR_EVAL_CELLS_UNAVAILABLE="eval_cells_unavailable";var RPC_ERROR_UNKNOWN_COMMAND="unknown_command",RPC_ERROR_TURN_ACTIVE="turn_active",RPC_ERROR_SESSION_BUSY="session_busy",RPC_ERROR_ATTACHED="attached",RPC_ERROR_INVALID_RELEASE_REASON="invalid_release_reason",RPC_ERROR_RELEASE_UNSUPPORTED="release_unsupported",RPC_ERROR_RELEASE_FAILED="release_failed",RPC_ERROR_HOST_DRAINING="host_draining";var STEER_WHEN_IDLE_CAPABILITY="steer_when_idle",USER_ACTIVITY_CAPABILITY="user_activity",SESSION_MODEL_SCOPE_CAPABILITY="session_model_scope";export{clientMessageIdentitySchema,clientMessageIdentity,readClientMessageIdentity,RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_SESSION_HELD,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_INVALID_PATH,RPC_ERROR_INVALID_ARGUMENT,RPC_ERROR_RESPONSE_TOO_LARGE,RPC_ERROR_RESPONSE_UNWRITABLE,RPC_ERROR_PROJECT_CWD_MISMATCH,RPC_ERROR_OPEN_FAILED,RPC_ERROR_OWNER_CHANGED,RPC_ERROR_MEDIA_NOT_FOUND,RPC_ERROR_PROJECT_TRUST_LOCKED,RPC_ERROR_PROJECT_TRUST_EXTENSION_DECIDED,RPC_ERROR_PROJECT_SETTINGS_WRITE_FAILED,RPC_ERROR_PROJECT_NOT_TRUSTED,RPC_ERROR_PROJECT_SETTINGS_UNREADABLE,RPC_ERROR_PROJECT_FILE_NOT_ALLOWED,RPC_ERROR_PROJECT_FILE_CONFLICT,RPC_ERROR_PROJECT_FILE_TOO_LARGE,RPC_ERROR_PROJECT_FILE_WRITE_FAILED,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_ENV,RPC_ERROR_INVALID_SUBSCRIPTION,RPC_ERROR_UNKNOWN_SUBSCRIPTION,RPC_ERROR_SUBSCRIPTION_LIMIT,RPC_ERROR_UNSUPPORTED_TRANSPORT,RPC_ERROR_FEATURE_DISABLED,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_WARM_FAILED,RPC_ERROR_ENTRY_NOT_FOUND,RPC_ERROR_MODEL_NOT_FOUND,RPC_ERROR_EFFECT_ID_CONFLICT,RPC_ERROR_TRANSCRIPT_UNREADABLE,RPC_ERROR_PROVIDER_UNAVAILABLE,RPC_ERROR_PROVIDER_CREDENTIALS_MISSING,RPC_ERROR_PROVIDER_CREDENTIALS_EXPIRED,RPC_ERROR_NO_MODEL_SELECTED,RPC_ERROR_TURN_CONFLICT,RPC_ERROR_CONTEXT_BUDGET,RPC_ERROR_EVAL_CELL_NOT_FOUND,RPC_ERROR_INVALID_EVAL_CELL_REQUEST,RPC_ERROR_EVAL_CELLS_UNAVAILABLE,RPC_ERROR_UNKNOWN_COMMAND,RPC_ERROR_TURN_ACTIVE,RPC_ERROR_SESSION_BUSY,RPC_ERROR_ATTACHED,RPC_ERROR_INVALID_RELEASE_REASON,RPC_ERROR_RELEASE_UNSUPPORTED,RPC_ERROR_RELEASE_FAILED,RPC_ERROR_HOST_DRAINING,STEER_WHEN_IDLE_CAPABILITY,USER_ACTIVITY_CAPABILITY,SESSION_MODEL_SCOPE_CAPABILITY};
@@ -1,2 +1,2 @@
1
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{signalSpawnedChild}from"./chunk-KLAX467B.js";import{getShellConfig}from"./chunk-JJYN347Z.js";import{rememberResolvedReferenceValue}from"./chunk-G7U4BOJP.js";import{Compile}from"./chunk-SFACYIB6.js";import{ConfigReferenceError}from"./chunk-OH5TKHW7.js";import{sanitizeProviderDiagnostic}from"./chunk-JGKH3D6W.js";import{attachProviderDiagnostic}from"./chunk-3SASTB6Y.js";import{typebox_exports}from"./chunk-MIENF2YK.js";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");attachProviderDiagnostic(failure,sanitizeProviderDiagnostic(event.error.providerDiagnostic));let status=event.error.providerDiagnostic?.httpStatus;return status===void 0?failure:Object.assign(failure,{status})}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{ConfigValueSchema,NonemptyConfigValueSchema,isConfigReference,warnOpaqueConfigEnvironment,warnMissingConfigEnvironment,rememberConfigReferenceOrigin,assertConfigReferenceAuthority,resolveConfigReference,sleep,getConfigValueEnvVarNames,isCommandConfigValue,isConfigValueConfigured,resolveConfigValue,resolveConfigValueOrThrow,resolveHeadersOrThrow,isCommittedRotationOutput,isRotationStreamStart,rotationErrorFromEvent};
2
+ import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{getShellConfig}from"./chunk-ZJUL5ODW.js";import{rememberResolvedReferenceValue}from"./chunk-G7U4BOJP.js";import{Compile}from"./chunk-IK3S2NDB.js";import{ConfigReferenceError}from"./chunk-OH5TKHW7.js";import{sanitizeProviderDiagnostic}from"./chunk-JGKH3D6W.js";import{attachProviderDiagnostic}from"./chunk-3SASTB6Y.js";import{typebox_exports}from"./chunk-MIENF2YK.js";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");attachProviderDiagnostic(failure,sanitizeProviderDiagnostic(event.error.providerDiagnostic));let status=event.error.providerDiagnostic?.httpStatus;return status===void 0?failure:Object.assign(failure,{status})}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{ConfigValueSchema,NonemptyConfigValueSchema,isConfigReference,warnOpaqueConfigEnvironment,warnMissingConfigEnvironment,rememberConfigReferenceOrigin,assertConfigReferenceAuthority,resolveConfigReference,sleep,getConfigValueEnvVarNames,isCommandConfigValue,isConfigValueConfigured,resolveConfigValue,resolveConfigValueOrThrow,resolveHeadersOrThrow,isCommittedRotationOutput,isRotationStreamStart,rotationErrorFromEvent};