@ai-agent-forge/agent-forge 0.87.0 → 0.88.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +2 -2
  3. package/dist/bundle/.build-manifest.json +65 -87
  4. package/dist/bundle/chunks/{chunk-BFC2BDVJ.js → chunk-HLJEVRWP.js} +2 -2
  5. package/dist/bundle/chunks/{chunk-MOHOLL3F.js → chunk-YGHQME4V.js} +72 -72
  6. package/dist/bundle/chunks/image-resize-worker.js +2 -2
  7. package/dist/bundle/cli.js +1 -1
  8. package/dist/bundle/client.js +1 -1
  9. package/dist/bundle/index.js +1 -1
  10. package/dist/bundle/rpc-entry.js +1 -1
  11. package/dist/cli/auth-check.d.ts.map +1 -1
  12. package/dist/cli/auth-check.js +14 -2
  13. package/dist/cli/auth-check.js.map +1 -1
  14. package/dist/cli/auth-command.d.ts.map +1 -1
  15. package/dist/cli/auth-command.js +1 -1
  16. package/dist/cli/auth-command.js.map +1 -1
  17. package/dist/config.d.ts.map +1 -1
  18. package/dist/config.js +3 -2
  19. package/dist/config.js.map +1 -1
  20. package/dist/core/agent-session-compaction.d.ts +6 -10
  21. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  22. package/dist/core/agent-session-compaction.js +7 -111
  23. package/dist/core/agent-session-compaction.js.map +1 -1
  24. package/dist/core/agent-session-internal.d.ts +0 -6
  25. package/dist/core/agent-session-internal.d.ts.map +1 -1
  26. package/dist/core/agent-session-internal.js.map +1 -1
  27. package/dist/core/agent-session-retry.d.ts.map +1 -1
  28. package/dist/core/agent-session-retry.js +0 -1
  29. package/dist/core/agent-session-retry.js.map +1 -1
  30. package/dist/core/agent-session.d.ts +0 -20
  31. package/dist/core/agent-session.d.ts.map +1 -1
  32. package/dist/core/agent-session.js +5 -33
  33. package/dist/core/agent-session.js.map +1 -1
  34. package/dist/core/extensions/bootstrap-compaction-policy.d.ts.map +1 -1
  35. package/dist/core/extensions/bootstrap-compaction-policy.js +0 -34
  36. package/dist/core/extensions/bootstrap-compaction-policy.js.map +1 -1
  37. package/dist/core/extensions/bootstrap-retry-policy.d.ts.map +1 -1
  38. package/dist/core/extensions/bootstrap-retry-policy.js +2 -2
  39. package/dist/core/extensions/bootstrap-retry-policy.js.map +1 -1
  40. package/dist/core/extensions/provider-failover.d.ts +7 -3
  41. package/dist/core/extensions/provider-failover.d.ts.map +1 -1
  42. package/dist/core/extensions/provider-failover.js +9 -8
  43. package/dist/core/extensions/provider-failover.js.map +1 -1
  44. package/dist/core/facade/coding-agent-facade.d.ts +0 -6
  45. package/dist/core/facade/coding-agent-facade.d.ts.map +1 -1
  46. package/dist/core/facade/coding-agent-facade.js +0 -3
  47. package/dist/core/facade/coding-agent-facade.js.map +1 -1
  48. package/dist/core/i18n/locales/zh-cn/cli.d.ts.map +1 -1
  49. package/dist/core/i18n/locales/zh-cn/cli.js +3 -1
  50. package/dist/core/i18n/locales/zh-cn/cli.js.map +1 -1
  51. package/dist/core/i18n/locales/zh-cn/interactive-mode.d.ts.map +1 -1
  52. package/dist/core/i18n/locales/zh-cn/interactive-mode.js +2 -0
  53. package/dist/core/i18n/locales/zh-cn/interactive-mode.js.map +1 -1
  54. package/dist/core/i18n/locales/zh-cn/tui-components-selectors.d.ts.map +1 -1
  55. package/dist/core/i18n/locales/zh-cn/tui-components-selectors.js +0 -2
  56. package/dist/core/i18n/locales/zh-cn/tui-components-selectors.js.map +1 -1
  57. package/dist/core/model-config.d.ts +0 -1
  58. package/dist/core/model-config.d.ts.map +1 -1
  59. package/dist/core/model-config.js +9 -1
  60. package/dist/core/model-config.js.map +1 -1
  61. package/dist/core/model-runtime.d.ts.map +1 -1
  62. package/dist/core/model-runtime.js +3 -3
  63. package/dist/core/model-runtime.js.map +1 -1
  64. package/dist/core/provider-composer.d.ts +2 -2
  65. package/dist/core/provider-composer.d.ts.map +1 -1
  66. package/dist/core/provider-composer.js +7 -8
  67. package/dist/core/provider-composer.js.map +1 -1
  68. package/dist/core/sdk.d.ts +8 -0
  69. package/dist/core/sdk.d.ts.map +1 -1
  70. package/dist/core/sdk.js +6 -1
  71. package/dist/core/sdk.js.map +1 -1
  72. package/dist/core/settings-manager.d.ts +9 -20
  73. package/dist/core/settings-manager.d.ts.map +1 -1
  74. package/dist/core/settings-manager.js +20 -54
  75. package/dist/core/settings-manager.js.map +1 -1
  76. package/dist/main.d.ts.map +1 -1
  77. package/dist/main.js +3 -2
  78. package/dist/main.js.map +1 -1
  79. package/dist/modes/interactive/components/footer.d.ts +0 -2
  80. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  81. package/dist/modes/interactive/components/footer.js +2 -7
  82. package/dist/modes/interactive/components/footer.js.map +1 -1
  83. package/dist/modes/interactive/components/settings-selector.d.ts +2 -6
  84. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  85. package/dist/modes/interactive/components/settings-selector.js +6 -28
  86. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  87. package/dist/modes/interactive/interactive-mode.d.ts +0 -1
  88. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  89. package/dist/modes/interactive/interactive-mode.js +23 -36
  90. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  91. package/dist/modes/rpc/rpc-client.d.ts +0 -8
  92. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  93. package/dist/modes/rpc/rpc-client.js +0 -12
  94. package/dist/modes/rpc/rpc-client.js.map +1 -1
  95. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  96. package/dist/modes/rpc/rpc-mode.js +0 -9
  97. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  98. package/dist/modes/rpc/rpc-types.d.ts +0 -19
  99. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  100. package/dist/modes/rpc/rpc-types.js.map +1 -1
  101. package/dist/plugins/ecosystem/node-plugin-bootstrap.d.ts +9 -2
  102. package/dist/plugins/ecosystem/node-plugin-bootstrap.d.ts.map +1 -1
  103. package/dist/plugins/ecosystem/node-plugin-bootstrap.js +23 -0
  104. package/dist/plugins/ecosystem/node-plugin-bootstrap.js.map +1 -1
  105. package/dist/plugins/ecosystem/plugin-bootstrap.d.ts +9 -1
  106. package/dist/plugins/ecosystem/plugin-bootstrap.d.ts.map +1 -1
  107. package/dist/plugins/ecosystem/plugin-bootstrap.js +5 -0
  108. package/dist/plugins/ecosystem/plugin-bootstrap.js.map +1 -1
  109. package/dist/utils/photon.d.ts +2 -2
  110. package/dist/utils/photon.d.ts.map +1 -1
  111. package/dist/utils/photon.js +2 -2
  112. package/dist/utils/photon.js.map +1 -1
  113. package/docs/compaction.md +1 -3
  114. package/docs/docs.json +4 -0
  115. package/docs/index.md +1 -0
  116. package/docs/mcp.md +103 -0
  117. package/docs/models.md +14 -22
  118. package/docs/providers.md +0 -1
  119. package/docs/rpc.md +1 -26
  120. package/docs/sdk.md +4 -6
  121. package/docs/settings.md +9 -12
  122. package/docs/skills.md +1 -9
  123. package/docs/usage.md +1 -1
  124. package/examples/extensions/with-deps/package-lock.json +2 -2
  125. package/examples/extensions/with-deps/package.json +1 -1
  126. package/examples/extensions/with-deps/plugin.json +1 -1
  127. package/examples/sdk/10-settings.ts +2 -4
  128. package/examples/sdk/12-full-control.ts +1 -2
  129. package/package.json +1 -3
  130. package/dist/core/extensions/microcompact.d.ts +0 -80
  131. package/dist/core/extensions/microcompact.d.ts.map +0 -1
  132. package/dist/core/extensions/microcompact.js +0 -134
  133. package/dist/core/extensions/microcompact.js.map +0 -1
  134. package/dist/server/create-harness.d.ts +0 -26
  135. package/dist/server/create-harness.d.ts.map +0 -1
  136. package/dist/server/create-harness.js +0 -106
  137. package/dist/server/create-harness.js.map +0 -1
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
3
- import{APP_NAME,configureHttpDispatcher,main}from"./chunks/chunk-MOHOLL3F.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-6ZKDNZHA.js";import"./chunks/chunk-XDUWOHPL.js";import"./chunks/chunk-3QKHSPQL.js";import"./chunks/chunk-BFC2BDVJ.js";import"./chunks/chunk-DRQDKNXA.js";import"./chunks/chunk-7ZY7IXZD.js";import"./chunks/chunk-Y7HXTASS.js";import"./chunks/chunk-CIX3FSBK.js";import"./chunks/chunk-4L3WN2XY.js";process.title=APP_NAME;process.env.AGENT_FORGE="true";process.env.AI_AGENT="agent-forge";process.emitWarning=(()=>{});configureHttpDispatcher();main(process.argv.slice(2));
3
+ import{APP_NAME,configureHttpDispatcher,main}from"./chunks/chunk-YGHQME4V.js";import"./chunks/chunk-JUUC5AZY.js";import"./chunks/chunk-6ZKDNZHA.js";import"./chunks/chunk-XDUWOHPL.js";import"./chunks/chunk-3QKHSPQL.js";import"./chunks/chunk-HLJEVRWP.js";import"./chunks/chunk-DRQDKNXA.js";import"./chunks/chunk-7ZY7IXZD.js";import"./chunks/chunk-Y7HXTASS.js";import"./chunks/chunk-CIX3FSBK.js";import"./chunks/chunk-4L3WN2XY.js";process.title=APP_NAME;process.env.AGENT_FORGE="true";process.env.AI_AGENT="agent-forge";process.emitWarning=(()=>{});configureHttpDispatcher();main(process.argv.slice(2));
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{t}from"./chunks/chunk-BFC2BDVJ.js";import"./chunks/chunk-4L3WN2XY.js";function isJsonValue(value){return value===null||typeof value=="boolean"||typeof value=="string"?!0:typeof value=="number"?Number.isFinite(value):Array.isArray(value)?value.every(isJsonValue):typeof value!="object"||Object.getPrototypeOf(value)!==Object.prototype?!1:Object.values(value).every(isJsonValue)}function parsePartialToolInput(value){try{let parsed=JSON.parse(value);if(isJsonValue(parsed))return parsed}catch{}return value}function createTranscriptState(snapshot){return{snapshot:structuredClone(snapshot),progressItems:new Map,progressOrder:[],toolCallBuffers:new Map}}function applyTranscriptSnapshot(state,snapshot){return state.snapshot.id===snapshot.id&&snapshot.revision<state.snapshot.revision?state:createTranscriptState(snapshot)}function applyTranscriptProgress(state,progress){if(progress.type==="item_started"||progress.type==="item_updated")return setProgressItem(state,progress.item);if(progress.type==="item_finished"){let toolCallBuffers2=new Map(state.toolCallBuffers);for(let key of toolCallBuffers2.keys())key.startsWith(`${progress.item.id}:`)&&toolCallBuffers2.delete(key);return setProgressItem({...state,toolCallBuffers:toolCallBuffers2},progress.item)}let item=state.progressItems.get(progress.messageId)??state.snapshot.transcript.find(({id})=>id===progress.messageId);if(!item||item.role!=="assistant")return state;let toolCallBuffers=state.toolCallBuffers,content=item.content.map((part,index)=>{if(index!==progress.contentIndex)return structuredClone(part);if(progress.kind==="text"&&part.type==="text")return{...part,text:part.text+progress.delta};if(progress.kind==="thinking"&&part.type==="thinking")return{...part,thinking:part.thinking+progress.delta};if(progress.kind==="toolCall"&&part.type==="toolCall"){let key=`${progress.messageId}:${progress.contentIndex}`,buffer=(state.toolCallBuffers.get(key)??(typeof part.input=="string"?part.input:""))+progress.delta;return toolCallBuffers=new Map(state.toolCallBuffers).set(key,buffer),{...part,input:parsePartialToolInput(buffer)}}return structuredClone(part)});return setProgressItem({...state,toolCallBuffers},{...item,content})}function selectTranscript(state){let transcript=state.snapshot.transcript.map(item=>state.progressItems.get(item.id)??item),ids=new Set(transcript.map(item=>item.id));for(let id of state.progressOrder){if(ids.has(id))continue;let item=state.progressItems.get(id);item&&(transcript.push(item),ids.add(id))}for(let item of state.snapshot.queuedSteer)ids.has(item.id)||(transcript.push(item),ids.add(item.id));return transcript}function setProgressItem(state,item){let progressItems=new Map(state.progressItems),progressOrder=progressItems.has(item.id)?state.progressOrder:[...state.progressOrder,item.id];return progressItems.set(item.id,structuredClone(item)),{...state,progressItems,progressOrder}}var RemoteSessionDisposedError=class extends Error{constructor(){super(t("Remote session is disposed")),this.name="RemoteSessionDisposedError"}};async function settleRemoteSessionDisposal(cleanup){let errors=(await Promise.allSettled(cleanup)).flatMap(result=>result.status==="rejected"&&!(result.reason instanceof RemoteSessionDisposedError)?[result.reason]:[]);if(errors.length===1)throw errors[0];if(errors.length>1)throw new AggregateError(errors,"Failed to dispose remote session")}var RemoteSession=class _RemoteSession{#client;#onListenerError;#lifecycle={status:"unbound"};#handle;#transcript;#unsubscribeSnapshot;#unsubscribeEvents;#listeners=new Set;#pendingAttachmentOperations=new Set;#activeOperationStates=new Set;#disposePromise;#resolveDisposeSignal=()=>{};#disposeSignal=new Promise(resolve=>{this.#resolveDisposeSignal=resolve});constructor(client,options={}){this.#client=client,this.#onListenerError=options.onListenerError}get id(){return this.#handle?.id}get state(){return{lifecycle:this.#lifecycle,snapshot:this.#transcript?.snapshot,transcript:this.#transcript?selectTranscript(this.#transcript):[]}}get snapshot(){return this.#transcript?.snapshot}get phase(){return this.snapshot?.phase}get operation(){return this.#lifecycle.status==="busy"?this.#lifecycle.operation:void 0}get models(){return this.#client.snapshot?.models??[]}get sessions(){return this.#client.snapshot?.sessions??[]}get connectionState(){return this.#client.connectionState}get disposed(){return this.#lifecycle.status==="disposed"}subscribe(listener){return this.#assertNotDisposed(),this.#listeners.add(listener),this.#callListener(listener,this.state),()=>this.#listeners.delete(listener)}onConnectionStateChange(listener){return this.#assertNotDisposed(),this.#client.onConnectionStateChange(listener)}static async open(client,sessionId,options={}){let session=new _RemoteSession(client,options);try{return await session.open(sessionId),session}catch(error){throw await session.dispose(),error}}async open(sessionId){this.#handle?.id===sessionId&&this.#lifecycle.status==="ready"||await this.#replace("open",()=>this.#client.acquireSession(sessionId,{mode:"exclusive"}))}static async create(client,createOptions,options={}){let session=new _RemoteSession(client,options);try{return await session.create(createOptions),session}catch(error){throw await session.dispose(),error}}async create(options){await this.#replace("create",()=>this.#client.createSession(options))}async submit(text){let normalized=text.trim();if(!normalized)return;this.#assertAvailable();let handle=this.#requireHandle();if(this.phase!=="idle"&&this.phase!=="turn")throw new Error(t("Session cannot accept input during {phase} phase",{phase:this.phase??"unknown"}));await this.#runOperation("submit",()=>(this.phase==="idle"?handle.prompt(normalized):handle.steer(normalized)).then(()=>{}))}async abort(){let preemptingSubmit=this.#lifecycle.status==="busy"&&this.#lifecycle.operation==="submit";preemptingSubmit?this.#assertNotDisposed():this.#assertAvailable();let handle=this.#requireHandle();this.phase==="idle"&&!preemptingSubmit||await this.#runOperation("abort",()=>handle.abort().then(()=>{}),preemptingSubmit)}async setModel(model){await this.#runIdleOperation("setModel","change model",()=>this.#requireHandle().setModel(model).then(()=>{}))}async setThinking(thinkingLevel){await this.#runIdleOperation("setThinking","change thinking level",()=>this.#requireHandle().setThinking(thinkingLevel).then(()=>{}))}async reconnect(){this.#assertAvailable();let sessionId=this.#requireHandle().id;await this.#runOperation("reconnect",()=>this.#trackAttachmentOperation(async()=>{await this.#client.reconnect();let handle=await this.#client.acquireSession(sessionId,{mode:"exclusive"});await this.#assertNotDisposedAfterAwait(handle),this.#bind(handle)}))}dispose(){if(this.#disposePromise)return this.#disposePromise;let handle=this.#handle;this.#lifecycle={status:"disposed"},this.#resolveDisposeSignal(),this.#clearSubscriptions(),this.#handle=void 0,this.#transcript=void 0;let cleanup=[...this.#pendingAttachmentOperations];return handle&&cleanup.push(handle.dispose()),this.#disposePromise=settleRemoteSessionDisposal(cleanup),this.#notify(),this.#listeners.clear(),this.#disposePromise}[Symbol.asyncDispose](){return this.dispose()}async#replace(operation,prepare){if(this.#assertAvailable(),this.#handle&&this.phase!=="idle")throw new Error(t("Cannot {operation} a session while session is {phase}",{operation,phase:this.phase??"unavailable"}));await this.#runOperation(operation,()=>this.#trackAttachmentOperation(()=>this.#prepareReplacement(operation,prepare)))}async#trackAttachmentOperation(run){let pending=run();this.#pendingAttachmentOperations.add(pending);try{await pending}finally{this.#pendingAttachmentOperations.delete(pending)}}async#prepareReplacement(operation,prepare){let previous=this.#handle,next=await prepare();await this.#assertNotDisposedAfterAwait(next);let snapshot=next.snapshot;if(!snapshot)throw await this.#detach(next),new Error(t("Session {id} did not provide a snapshot",{id:next.id}));if(previous&&previous.id!==next.id&&previous.attached&&this.phase!=="idle")throw await this.#detach(next),new Error(t("Cannot {operation} a session while session is {phase}",{operation,phase:this.phase??"unavailable"}));if(previous&&previous.id!==next.id&&previous.attached)try{await previous.detach()}catch(error){try{await this.#detach(next)}catch(cleanupError){throw new AggregateError([error,cleanupError],"Failed to replace remote session attachment")}throw error}await this.#assertNotDisposedAfterAwait(next),this.#bind(next,snapshot)}async#runIdleOperation(operation,description,run){if(this.#assertAvailable(),this.#requireHandle(),this.phase!=="idle")throw new Error(t("Cannot {description} while session is {phase}",{description,phase:this.phase??"unavailable"}));await this.#runOperation(operation,run)}async#runOperation(operation,run,preempt=!1){preempt?this.#assertNotDisposed():this.#assertAvailable();let previous=this.#lifecycle,busy={status:"busy",operation};this.#lifecycle=busy,this.#activeOperationStates.add(busy),this.#notify();let running=run();try{await Promise.race([running,this.#disposeSignal.then(()=>{throw new Error(t("Remote session is disposed"))})])}finally{this.#activeOperationStates.delete(busy),!this.disposed&&this.#lifecycle===busy&&(this.#lifecycle=preempt&&this.#activeOperationStates.has(previous)?previous:this.#handle?{status:"ready"}:{status:"unbound"},this.#notify())}}#bind(handle,knownSnapshot){let snapshot=knownSnapshot??handle.snapshot;if(!snapshot)throw new Error(`Session ${handle.id} did not provide a snapshot`);this.#clearSubscriptions(),this.#handle=handle,this.#transcript=createTranscriptState(snapshot),this.#unsubscribeSnapshot=handle.subscribe(next=>{this.#transcript&&(this.#transcript=applyTranscriptSnapshot(this.#transcript,next),this.#notify())}),this.#unsubscribeEvents=handle.onEvent(event=>this.#handleEvent(event))}#handleEvent(event){if(event.type==="session_removed"){this.#clearSubscriptions(),this.#handle=void 0,this.#transcript=void 0,this.#lifecycle.status!=="busy"&&(this.#lifecycle={status:"unbound"}),this.#notify();return}event.type!=="session_progress"||!this.#transcript||(this.#transcript=applyTranscriptProgress(this.#transcript,event.progress),this.#notify())}#notify(){let state=this.state;for(let listener of this.#listeners)this.#callListener(listener,state)}#callListener(listener,state){try{listener(state)}catch(error){this.#reportListenerError(error)}}#reportListenerError(error){if(this.#onListenerError)try{this.#onListenerError(error instanceof Error?error:new Error(String(error)))}catch{}}#clearSubscriptions(){this.#unsubscribeSnapshot?.(),this.#unsubscribeEvents?.(),this.#unsubscribeSnapshot=void 0,this.#unsubscribeEvents=void 0}#requireHandle(){if(!this.#handle)throw new Error("No remote session is attached");return this.#handle}#assertAvailable(){if(this.#assertNotDisposed(),this.#lifecycle.status==="busy")throw new Error(t("Remote session is busy with {operation}",{operation:this.#lifecycle.operation}))}#assertNotDisposed(){if(this.disposed)throw new Error(t("Remote session is disposed"))}async#assertNotDisposedAfterAwait(handle){if(this.disposed)throw await this.#detach(handle),new RemoteSessionDisposedError}async#detach(handle){await handle.dispose()}};export{RemoteSession,applyTranscriptProgress,applyTranscriptSnapshot,createTranscriptState,selectTranscript};
2
+ import{t}from"./chunks/chunk-HLJEVRWP.js";import"./chunks/chunk-4L3WN2XY.js";function isJsonValue(value){return value===null||typeof value=="boolean"||typeof value=="string"?!0:typeof value=="number"?Number.isFinite(value):Array.isArray(value)?value.every(isJsonValue):typeof value!="object"||Object.getPrototypeOf(value)!==Object.prototype?!1:Object.values(value).every(isJsonValue)}function parsePartialToolInput(value){try{let parsed=JSON.parse(value);if(isJsonValue(parsed))return parsed}catch{}return value}function createTranscriptState(snapshot){return{snapshot:structuredClone(snapshot),progressItems:new Map,progressOrder:[],toolCallBuffers:new Map}}function applyTranscriptSnapshot(state,snapshot){return state.snapshot.id===snapshot.id&&snapshot.revision<state.snapshot.revision?state:createTranscriptState(snapshot)}function applyTranscriptProgress(state,progress){if(progress.type==="item_started"||progress.type==="item_updated")return setProgressItem(state,progress.item);if(progress.type==="item_finished"){let toolCallBuffers2=new Map(state.toolCallBuffers);for(let key of toolCallBuffers2.keys())key.startsWith(`${progress.item.id}:`)&&toolCallBuffers2.delete(key);return setProgressItem({...state,toolCallBuffers:toolCallBuffers2},progress.item)}let item=state.progressItems.get(progress.messageId)??state.snapshot.transcript.find(({id})=>id===progress.messageId);if(!item||item.role!=="assistant")return state;let toolCallBuffers=state.toolCallBuffers,content=item.content.map((part,index)=>{if(index!==progress.contentIndex)return structuredClone(part);if(progress.kind==="text"&&part.type==="text")return{...part,text:part.text+progress.delta};if(progress.kind==="thinking"&&part.type==="thinking")return{...part,thinking:part.thinking+progress.delta};if(progress.kind==="toolCall"&&part.type==="toolCall"){let key=`${progress.messageId}:${progress.contentIndex}`,buffer=(state.toolCallBuffers.get(key)??(typeof part.input=="string"?part.input:""))+progress.delta;return toolCallBuffers=new Map(state.toolCallBuffers).set(key,buffer),{...part,input:parsePartialToolInput(buffer)}}return structuredClone(part)});return setProgressItem({...state,toolCallBuffers},{...item,content})}function selectTranscript(state){let transcript=state.snapshot.transcript.map(item=>state.progressItems.get(item.id)??item),ids=new Set(transcript.map(item=>item.id));for(let id of state.progressOrder){if(ids.has(id))continue;let item=state.progressItems.get(id);item&&(transcript.push(item),ids.add(id))}for(let item of state.snapshot.queuedSteer)ids.has(item.id)||(transcript.push(item),ids.add(item.id));return transcript}function setProgressItem(state,item){let progressItems=new Map(state.progressItems),progressOrder=progressItems.has(item.id)?state.progressOrder:[...state.progressOrder,item.id];return progressItems.set(item.id,structuredClone(item)),{...state,progressItems,progressOrder}}var RemoteSessionDisposedError=class extends Error{constructor(){super(t("Remote session is disposed")),this.name="RemoteSessionDisposedError"}};async function settleRemoteSessionDisposal(cleanup){let errors=(await Promise.allSettled(cleanup)).flatMap(result=>result.status==="rejected"&&!(result.reason instanceof RemoteSessionDisposedError)?[result.reason]:[]);if(errors.length===1)throw errors[0];if(errors.length>1)throw new AggregateError(errors,"Failed to dispose remote session")}var RemoteSession=class _RemoteSession{#client;#onListenerError;#lifecycle={status:"unbound"};#handle;#transcript;#unsubscribeSnapshot;#unsubscribeEvents;#listeners=new Set;#pendingAttachmentOperations=new Set;#activeOperationStates=new Set;#disposePromise;#resolveDisposeSignal=()=>{};#disposeSignal=new Promise(resolve=>{this.#resolveDisposeSignal=resolve});constructor(client,options={}){this.#client=client,this.#onListenerError=options.onListenerError}get id(){return this.#handle?.id}get state(){return{lifecycle:this.#lifecycle,snapshot:this.#transcript?.snapshot,transcript:this.#transcript?selectTranscript(this.#transcript):[]}}get snapshot(){return this.#transcript?.snapshot}get phase(){return this.snapshot?.phase}get operation(){return this.#lifecycle.status==="busy"?this.#lifecycle.operation:void 0}get models(){return this.#client.snapshot?.models??[]}get sessions(){return this.#client.snapshot?.sessions??[]}get connectionState(){return this.#client.connectionState}get disposed(){return this.#lifecycle.status==="disposed"}subscribe(listener){return this.#assertNotDisposed(),this.#listeners.add(listener),this.#callListener(listener,this.state),()=>this.#listeners.delete(listener)}onConnectionStateChange(listener){return this.#assertNotDisposed(),this.#client.onConnectionStateChange(listener)}static async open(client,sessionId,options={}){let session=new _RemoteSession(client,options);try{return await session.open(sessionId),session}catch(error){throw await session.dispose(),error}}async open(sessionId){this.#handle?.id===sessionId&&this.#lifecycle.status==="ready"||await this.#replace("open",()=>this.#client.acquireSession(sessionId,{mode:"exclusive"}))}static async create(client,createOptions,options={}){let session=new _RemoteSession(client,options);try{return await session.create(createOptions),session}catch(error){throw await session.dispose(),error}}async create(options){await this.#replace("create",()=>this.#client.createSession(options))}async submit(text){let normalized=text.trim();if(!normalized)return;this.#assertAvailable();let handle=this.#requireHandle();if(this.phase!=="idle"&&this.phase!=="turn")throw new Error(t("Session cannot accept input during {phase} phase",{phase:this.phase??"unknown"}));await this.#runOperation("submit",()=>(this.phase==="idle"?handle.prompt(normalized):handle.steer(normalized)).then(()=>{}))}async abort(){let preemptingSubmit=this.#lifecycle.status==="busy"&&this.#lifecycle.operation==="submit";preemptingSubmit?this.#assertNotDisposed():this.#assertAvailable();let handle=this.#requireHandle();this.phase==="idle"&&!preemptingSubmit||await this.#runOperation("abort",()=>handle.abort().then(()=>{}),preemptingSubmit)}async setModel(model){await this.#runIdleOperation("setModel","change model",()=>this.#requireHandle().setModel(model).then(()=>{}))}async setThinking(thinkingLevel){await this.#runIdleOperation("setThinking","change thinking level",()=>this.#requireHandle().setThinking(thinkingLevel).then(()=>{}))}async reconnect(){this.#assertAvailable();let sessionId=this.#requireHandle().id;await this.#runOperation("reconnect",()=>this.#trackAttachmentOperation(async()=>{await this.#client.reconnect();let handle=await this.#client.acquireSession(sessionId,{mode:"exclusive"});await this.#assertNotDisposedAfterAwait(handle),this.#bind(handle)}))}dispose(){if(this.#disposePromise)return this.#disposePromise;let handle=this.#handle;this.#lifecycle={status:"disposed"},this.#resolveDisposeSignal(),this.#clearSubscriptions(),this.#handle=void 0,this.#transcript=void 0;let cleanup=[...this.#pendingAttachmentOperations];return handle&&cleanup.push(handle.dispose()),this.#disposePromise=settleRemoteSessionDisposal(cleanup),this.#notify(),this.#listeners.clear(),this.#disposePromise}[Symbol.asyncDispose](){return this.dispose()}async#replace(operation,prepare){if(this.#assertAvailable(),this.#handle&&this.phase!=="idle")throw new Error(t("Cannot {operation} a session while session is {phase}",{operation,phase:this.phase??"unavailable"}));await this.#runOperation(operation,()=>this.#trackAttachmentOperation(()=>this.#prepareReplacement(operation,prepare)))}async#trackAttachmentOperation(run){let pending=run();this.#pendingAttachmentOperations.add(pending);try{await pending}finally{this.#pendingAttachmentOperations.delete(pending)}}async#prepareReplacement(operation,prepare){let previous=this.#handle,next=await prepare();await this.#assertNotDisposedAfterAwait(next);let snapshot=next.snapshot;if(!snapshot)throw await this.#detach(next),new Error(t("Session {id} did not provide a snapshot",{id:next.id}));if(previous&&previous.id!==next.id&&previous.attached&&this.phase!=="idle")throw await this.#detach(next),new Error(t("Cannot {operation} a session while session is {phase}",{operation,phase:this.phase??"unavailable"}));if(previous&&previous.id!==next.id&&previous.attached)try{await previous.detach()}catch(error){try{await this.#detach(next)}catch(cleanupError){throw new AggregateError([error,cleanupError],"Failed to replace remote session attachment")}throw error}await this.#assertNotDisposedAfterAwait(next),this.#bind(next,snapshot)}async#runIdleOperation(operation,description,run){if(this.#assertAvailable(),this.#requireHandle(),this.phase!=="idle")throw new Error(t("Cannot {description} while session is {phase}",{description,phase:this.phase??"unavailable"}));await this.#runOperation(operation,run)}async#runOperation(operation,run,preempt=!1){preempt?this.#assertNotDisposed():this.#assertAvailable();let previous=this.#lifecycle,busy={status:"busy",operation};this.#lifecycle=busy,this.#activeOperationStates.add(busy),this.#notify();let running=run();try{await Promise.race([running,this.#disposeSignal.then(()=>{throw new Error(t("Remote session is disposed"))})])}finally{this.#activeOperationStates.delete(busy),!this.disposed&&this.#lifecycle===busy&&(this.#lifecycle=preempt&&this.#activeOperationStates.has(previous)?previous:this.#handle?{status:"ready"}:{status:"unbound"},this.#notify())}}#bind(handle,knownSnapshot){let snapshot=knownSnapshot??handle.snapshot;if(!snapshot)throw new Error(`Session ${handle.id} did not provide a snapshot`);this.#clearSubscriptions(),this.#handle=handle,this.#transcript=createTranscriptState(snapshot),this.#unsubscribeSnapshot=handle.subscribe(next=>{this.#transcript&&(this.#transcript=applyTranscriptSnapshot(this.#transcript,next),this.#notify())}),this.#unsubscribeEvents=handle.onEvent(event=>this.#handleEvent(event))}#handleEvent(event){if(event.type==="session_removed"){this.#clearSubscriptions(),this.#handle=void 0,this.#transcript=void 0,this.#lifecycle.status!=="busy"&&(this.#lifecycle={status:"unbound"}),this.#notify();return}event.type!=="session_progress"||!this.#transcript||(this.#transcript=applyTranscriptProgress(this.#transcript,event.progress),this.#notify())}#notify(){let state=this.state;for(let listener of this.#listeners)this.#callListener(listener,state)}#callListener(listener,state){try{listener(state)}catch(error){this.#reportListenerError(error)}}#reportListenerError(error){if(this.#onListenerError)try{this.#onListenerError(error instanceof Error?error:new Error(String(error)))}catch{}}#clearSubscriptions(){this.#unsubscribeSnapshot?.(),this.#unsubscribeEvents?.(),this.#unsubscribeSnapshot=void 0,this.#unsubscribeEvents=void 0}#requireHandle(){if(!this.#handle)throw new Error("No remote session is attached");return this.#handle}#assertAvailable(){if(this.#assertNotDisposed(),this.#lifecycle.status==="busy")throw new Error(t("Remote session is busy with {operation}",{operation:this.#lifecycle.operation}))}#assertNotDisposed(){if(this.disposed)throw new Error(t("Remote session is disposed"))}async#assertNotDisposedAfterAwait(handle){if(this.disposed)throw await this.#detach(handle),new RemoteSessionDisposedError}async#detach(handle){await handle.dispose()}};export{RemoteSession,applyTranscriptProgress,applyTranscriptSnapshot,createTranscriptState,selectTranscript};