@tencent-ai/agent-harness 0.2.0-beta.10 → 0.2.0-beta.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/cli/CHANGELOG.md +42 -0
- package/cli/dist-server/shared.cjs +316 -315
- package/cli/dist-server/types/node/agent/agent-controller.d.ts +1 -0
- package/cli/dist-server/types/node/agent/index.d.ts +1 -0
- package/cli/dist-server/types/node/agent/interceptors/image-interceptors.d.ts +1 -2
- package/cli/dist-server/types/node/agent/interceptors/sandbox-interceptor.d.ts +1 -0
- package/cli/dist-server/types/node/agent/steer-model-input-preparer.d.ts +11 -0
- package/cli/dist-server/types/node/agent-task/agent-task.d.ts +12 -0
- package/cli/dist-server/types/node/agent-team/backends/teammate-backend-protocol.d.ts +2 -0
- package/cli/dist-server/types/node/agent-view/session-handoff.d.ts +7 -0
- package/cli/dist-server/types/node/channel/channel-protocol.d.ts +8 -8
- package/cli/dist-server/types/node/cli/cli-runtime-options.d.ts +24 -1
- package/cli/dist-server/types/node/command/clear-command-executor.d.ts +2 -0
- package/cli/dist-server/types/node/hooks/hook-protocol.d.ts +3 -67
- package/cli/dist-server/types/node/loopback/endpoint-provider.d.ts +3 -0
- package/cli/dist-server/types/node/loopback/server-protocol.d.ts +7 -0
- package/cli/dist-server/types/node/memory/memory-relevance-protocol.d.ts +6 -1
- package/cli/dist-server/types/node/memory/memory-relevance-service.d.ts +3 -2
- package/cli/dist-server/types/node/model/model-protocol.d.ts +4 -0
- package/cli/dist-server/types/node/security-review/gate.d.ts +1 -0
- package/cli/dist-server/types/node/security-review/protocol.d.ts +2 -0
- package/cli/dist-server/types/node/session/session-hook-host-adapter.d.ts +2 -2
- package/cli/dist-server/types/node/settings/current-session-model-transition.d.ts +5 -4
- package/cli/dist-server/types/node/settings/settings-protocol.d.ts +2 -0
- package/cli/dist-server/types/node/tools/a2a-cancel-task-tool.d.ts +4 -4
- package/cli/dist-server/types/node/tools/a2a-get-task-tool.d.ts +4 -4
- package/cli/dist-server/types/node/tools/audio-transcribe-tool.d.ts +1 -2
- package/cli/dist-server/types/node/tools/grep-tool.d.ts +2 -0
- package/cli/dist-server/types/node/tools/image-service.d.ts +3 -1
- package/cli/dist-server/types/node/tools/index.d.ts +1 -0
- package/cli/dist-server/types/node/tools/media-file-writer.d.ts +12 -0
- package/cli/dist-server/types/node/tools/multi-edit-tool.d.ts +4 -4
- package/cli/dist-server/types/node/tools/powershell-tool.d.ts +2 -0
- package/cli/dist-server/types/node/tools/send-message-tool.d.ts +2 -2
- package/cli/dist-server/types/node/tools/tool-hook-manager.d.ts +2 -2
- package/cli/dist-server/types/node/tools/tool-manager.d.ts +1 -0
- package/cli/dist-server/types/node/tools/tool-protocol.d.ts +2 -2
- package/cli/dist-server/types/node/tools/video-service.d.ts +2 -0
- package/cli/dist-server/types/node/tools/wecom-reply-tool.d.ts +2 -2
- package/cli/dist-server/types/vendor/cbc-core/node/agent/agent-protocol.d.ts +12 -0
- package/cli/dist-server/types/vendor/cbc-core/node/agent/agent-service.d.ts +11 -0
- package/cli/dist-server/types/vendor/cbc-core/node/agent/index.d.ts +1 -0
- package/cli/dist-server/types/vendor/cbc-core/node/agent/runner-factory.d.ts +6 -0
- package/cli/dist-server/types/vendor/cbc-core/node/context/compact-strategy-base.d.ts +17 -5
- package/cli/dist-server/types/vendor/cbc-core/node/context/pre-switch-model.d.ts +34 -0
- package/cli/dist-server/types/vendor/cbc-core/node/hooks/hook-protocol.d.ts +118 -3
- package/cli/dist-server/types/vendor/cbc-core/node/message-queue/index.d.ts +1 -0
- package/cli/dist-server/types/vendor/cbc-core/node/message-queue/injectable-content.d.ts +15 -18
- package/cli/dist-server/types/vendor/cbc-core/node/message-queue/steer-input-buffer-protocol.d.ts +12 -13
- package/cli/dist-server/types/vendor/cbc-core/node/message-queue/steer-input-buffer.d.ts +1 -2
- package/cli/dist-server/types/vendor/cbc-core/node/message-queue/steer-model-input-preparer-protocol.d.ts +13 -0
- package/cli/dist-server/types/vendor/cbc-core/node/session/interruption-service.d.ts +11 -0
- package/cli/dist-server/types/vendor/cbc-core/node/session/session-fork-guard.d.ts +2 -1
- package/cli/dist-server/types/vendor/cbc-core/node/session/session-hook-manager.d.ts +2 -2
- package/cli/dist-server/types/vendor/cbc-core/node/session/session-manager.d.ts +9 -0
- package/cli/dist-server/types/vendor/cbc-core/node/session/session-protocol.d.ts +9 -2
- package/cli/dist-server/types/vendor/cbc-core/node/session/session-store.d.ts +3 -3
- package/cli/dist-server/types/vendor/cbc-core/node/trace/trace-turn-gate.d.ts +13 -0
- package/cli/dist-server/types/vendor/cbc-core/node/utils/error-utils.d.ts +7 -0
- package/cli/dist-server/types/vendor/cbc-core/node/utils/index.d.ts +2 -0
- package/cli/dist-server/types/vendor/cbc-core/node/utils/markdown-code-utils.d.ts +15 -0
- package/cli/dist-server/types/vendor/cbc-core/node/utils/message-content-utils.d.ts +3 -1
- package/cli/dist-server/types/vendor/cbc-core/node/utils/responses-api-utils.d.ts +21 -0
- package/cli/dist-server/types/vendor/cbc-core/node/utils/session-utils.d.ts +20 -0
- package/cli/dist-server/types/vendor/cbc-core/node/utils/usage-utils.d.ts +18 -0
- package/cli/dist-server/types/vendor/cbc-shared/node/agent/openai-agents-types.d.ts +3 -1
- package/cli/dist-server/types/vendor/cbc-shared/node/index.d.ts +1 -0
- package/cli/dist-server/types/vendor/cbc-shared/node/logging/structured-event-log.d.ts +64 -0
- package/cli/dist-server/types/vendor/cbc-shared/node/model/model-errors.d.ts +10 -0
- package/cli/dist-server/types/workspace/authentication/lib/common/authentication-http-interceptor.d.ts +1 -15
- package/cli/dist-server/types/workspace/authentication/lib/common/authentication-manager.d.ts +13 -0
- package/cli/dist-server/types/workspace/authentication/lib/common/authentication-protocol.d.ts +7 -0
- package/cli/dist-server/types/workspace/authentication/lib/common/authentication-refresh-bypass.d.ts +9 -0
- package/cli/dist-server/types/workspace/authentication/lib/common/index.d.ts +1 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/agent-protocol.d.ts +12 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/agent-service.d.ts +11 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/index.d.ts +1 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/runner-factory.d.ts +6 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/context/compact-strategy-base.d.ts +17 -5
- package/cli/dist-server/types/workspace/cbc-core/lib/node/context/pre-switch-model.d.ts +34 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/hooks/hook-protocol.d.ts +118 -3
- package/cli/dist-server/types/workspace/cbc-core/lib/node/message-queue/index.d.ts +1 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/message-queue/injectable-content.d.ts +15 -18
- package/cli/dist-server/types/workspace/cbc-core/lib/node/message-queue/steer-input-buffer-protocol.d.ts +12 -13
- package/cli/dist-server/types/workspace/cbc-core/lib/node/message-queue/steer-input-buffer.d.ts +1 -2
- package/cli/dist-server/types/workspace/cbc-core/lib/node/message-queue/steer-model-input-preparer-protocol.d.ts +13 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/interruption-service.d.ts +11 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-fork-guard.d.ts +2 -1
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-hook-manager.d.ts +2 -2
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-manager.d.ts +9 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-protocol.d.ts +9 -2
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-store.d.ts +3 -3
- package/cli/dist-server/types/workspace/cbc-core/lib/node/trace/trace-turn-gate.d.ts +13 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/error-utils.d.ts +7 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/index.d.ts +2 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/markdown-code-utils.d.ts +15 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/message-content-utils.d.ts +3 -1
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/responses-api-utils.d.ts +21 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/session-utils.d.ts +20 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/usage-utils.d.ts +18 -0
- package/cli/dist-server/types/workspace/cbc-daemon/lib/node/daemon/daemon-auto-restart.d.ts +2 -2
- package/cli/dist-server/types/workspace/cbc-daemon/lib/node/daemon/daemon-protocol.d.ts +17 -1
- package/cli/dist-server/types/workspace/cbc-plugins/lib/node/mods/engine/enable-flag.d.ts +28 -24
- package/cli/dist-server/types/workspace/cbc-plugins/lib/node/mods/loader/bootstrap.d.ts +2 -2
- package/cli/dist-server/types/workspace/cbc-shared/lib/node/agent/openai-agents-types.d.ts +3 -1
- package/cli/dist-server/types/workspace/cbc-shared/lib/node/index.d.ts +1 -0
- package/cli/dist-server/types/workspace/cbc-shared/lib/node/logging/structured-event-log.d.ts +64 -0
- package/cli/dist-server/types/workspace/cbc-shared/lib/node/model/model-errors.d.ts +10 -0
- package/cli/dist-server/types/workspace/core/lib/common/utils/env-utils.d.ts +12 -1
- package/cli/dist-server/types/workspace/product/lib/common/model-catalog/index.d.ts +2 -0
- package/cli/dist-server/types/workspace/product/lib/common/types/features.d.ts +36 -0
- package/cli/dist-server/types/workspace/product/lib/common/types/language-model.d.ts +7 -0
- package/cli/dist-server/types/workspace/sandbox-cli/lib/node/sandbox-center-client.d.ts +1 -1
- package/cli/dist-server/types/workspace/telemetry/lib/common/event/types/craft.d.ts +2 -1
- package/cli/dist-server/types/workspace/telemetry/lib/common/tracing/index.d.ts +2 -2
- package/cli/dist-server/types/workspace/telemetry/lib/common/tracing/otel-env.d.ts +16 -5
- package/cli/dist-server/types/workspace/telemetry/lib/common/tracing/trace-protocol.d.ts +9 -0
- package/cli/package.json +1 -1
- package/cli/product.cloudhosted.json +1 -1
- package/cli/product.internal.json +1 -1
- package/cli/product.ioa.json +1 -1
- package/cli/product.json +1 -1
- package/cli/product.selfhosted.json +1 -1
- package/cli/vendor/shim/node-safe-delete-shim.cjs +20 -3
- package/cli/vendor/shim/sitecustomize.py +17 -4
- package/docs/acp-v2.md +21 -2
- package/docs/client.md +44 -0
- package/docs/errors.md +1 -0
- package/docs/in-process.md +1 -0
- package/lib/agent/v2.js +1 -1
- package/lib/application/services.d.ts +1 -0
- package/lib/application/services.js +1 -1
- package/lib/cli/main.js +3 -3
- package/lib/cli/options.d.ts +2 -1
- package/lib/cli/options.js +4 -2
- package/lib/harness/runtime.js +1 -1
- package/lib/harness/types.d.ts +2 -0
- package/lib/runtime/component-protocol.js +1 -1
- package/package.json +9 -9
|
@@ -22,6 +22,7 @@ export interface ApplicationServicesOptions {
|
|
|
22
22
|
readonly tools?: QueryOptions['tools'];
|
|
23
23
|
readonly hooks?: HarnessHooks;
|
|
24
24
|
readonly strictMcpConfig: boolean;
|
|
25
|
+
readonly maxActiveSessions?: number;
|
|
25
26
|
readonly mcp?: {
|
|
26
27
|
readonly toolsSyncTtlMs?: number | null;
|
|
27
28
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var ir=Object.defineProperty;var t=(l,P)=>ir(l,"name",{value:P,configurable:!0});import{homedir as Le}from"node:os";import*as I from"node:path";import{isDeepStrictEqual as ar}from"node:util";import{Cause as Te,Context as d,Effect as a,Exit as h,Layer as p,Logger as ie,Option as sr,Scope as m}from"effect";import{WORKBUDDY_ENABLE_LINUX_SANDBOX_CLI as xe}from"#agent-harness-components/sandbox";import{createAgentProtocolModule as cr}from"../agent/router.js";import{createAgentV2Facade as dr}from"../agent/v2.js";import{ManagedAuthLocal as ur}from"../auth/local.js";import{ManagedAuth as pr}from"../auth/managed.js";import{createAuthProtocolModule as mr}from"../auth/module.js";import{Checkpoints as Oe}from"../checkpoint/service.js";import{ConfigFiles as ae}from"../config/files.js";import{HostHooks as Ue}from"../harness/hooks.js";import{createDefaultAgentMcpIntegration as lr}from"../integration/agent-integration.js";import{PluginMcp as He}from"../integration/plugin-mcp.js";import{UserMcp as Fe}from"../integration/user-mcp.js";import{requestWithEnvironment as fr}from"../internal/http.js";import{createMcpServerProtocolModule as hr}from"../mcp-server/module.js";import{composeAgentHarnessModules as gr}from"../module/compose.js";import{PluginComponents as se}from"../plugin/components.js";import{createProductProtocolModule as yr}from"../product/module.js";import{preflightCodeBuddyCode as vr}from"../runtime/agent-runtime.js";import{buildAgentHarnessClientIdentityEnv as Er,buildAgentHarnessClientIdentityHeaders as Sr}from"../runtime/client-identity.js";import{createCodeBuddyAuthRuntime as Pr}from"../runtime/codebuddy-auth.js";import{createCodeBuddyProductLifecycle as Cr}from"../runtime/codebuddy-product.js";import{DEFAULT_HOST_HEALTH_TIMEOUT_MS as wr,DEFAULT_READY_TIMEOUT_MS as Ar}from"../runtime/codebuddy-resource-timeouts.js";import{CodeBuddyProcessContainment as kr}from"../runtime/process-containment.js";import{parseAgentHarnessProductConfig as _r,parseHarnessProductInput as br}from"../runtime/product-config.js";import{ProductManager as Dr}from"../runtime/product-manager.js";import{ProductResolver as Be}from"../runtime/product-resolver.js";import{ProductResolverRequestError as Mr}from"../runtime/product-resolver-error.js";import{loadProductSource as Ir}from"../runtime/product-source.js";import{HarnessSandboxCenter as Rr}from"../runtime/sandbox-center.js";import{AgentHarnessServer as Lr,DEFAULT_LIFECYCLE_HOOK_TIMEOUT_MS as Tr}from"../server/index.js";import{makeServiceRpcs as xr}from"../server/rpc-services.js";import{AgentBackend as Or,workspaceQueryOptions as Ur}from"../session/agent-backend.js";import{AgentServer as ze}from"../session/agent-server.js";import{readSessionConfigDefaults as Hr}from"../session/config-defaults.js";import{SessionConfigStore as Fr}from"../session/config-store.js";import{SessionFiles as Br}from"../session/files.js";import{localFs as Ne}from"../session/local-fs.js";import{SessionReplay as We}from"../session/replay.js";import{SessionRuntime as zr}from"../session/runtime.js";import{Sessions as Ye}from"../session/service.js";import{toExecutorPrivateProxyPolicy as qe}from"../settings/proxy-policy.js";import{createHarnessSettingsRuntime as Nr}from"../settings/runtime.js";import{Settings as Wr}from"../settings/service.js";import{createSubagentProtocolModule as Yr}from"../subagent/module.js";import{createEffectTelemetryMetricAggregator as qr}from"../telemetry/effect-metric-aggregation.js";import{createTelemetry as Gr}from"../telemetry/runtime.js";import{measureStartup as ce,startupProfiler as s}from"../telemetry/startup-profile.js";import{closeInPhases as H,closeTelemetry as jr,createCloseOnce as k,DEFAULT_TELEMETRY_CLOSE_TIMEOUT_MS as Kr,withNativeShutdownTimeout as Vr}from"./lifecycle.js";const F=ie.layer([ie.withConsoleError(ie.formatLogFmt)]);export class Application extends d.Service()("@genie/agent-harness/application/Application"){static{t(this,"Application")}static layer(P){return p.fromBuildMemo((f,R)=>a.gen(function*(){const g=yield*a.tryPromise({try:t(()=>Xr(P,R,f),"try"),catch:t(b=>b,"catch")});return d.make(Application,g)}).pipe(a.uninterruptible))}}export async function createApplicationServices(l){const P=m.makeUnsafe(),f=k(g=>a.runPromise(m.close(P,g===void 0?h.void:h.fail(g)))),R=l.processRuntime.addFinalizer(()=>f());try{return d.get(await a.runPromise(p.buildWithScope(Application.layer(l),P)),Application)}catch(g){throw await H([[()=>f(g)]],l.shutdown,"application acquisition cleanup").then(R,()=>{}),g}}t(createApplicationServices,"createApplicationServices");async function Xr({clientIdentity:l,clientIdentityEnv:P,dependencies:f,packageVersion:R,processRuntime:g,productConfig:b,sandboxCenter:Ge,tools:de,hooks:je,strictMcpConfig:Ke,mcp:Ve,shutdown:D,telemetryOptions:ue,signal:u},pe,me){u?.throwIfAborted();const le=t(async e=>{const i=await a.runPromiseExit(e,{signal:u});if(h.isSuccess(i))return i.value;throw u?.aborted&&Te.hasInterruptsOnly(i.cause)?u.reason:Te.squash(i.cause)},"runStartupEffect"),C=t((e,i)=>le(p.buildWithMemoMap(e,me,i)),"build"),w=t(e=>a.runSync(m.addFinalizerExit(pe,()=>a.promise(()=>Vr(Promise.resolve().then(e),Math.max(1,Math.min(D.phaseMs,D.remainingMs())),"application resource release")))),"addFinalizer"),Y=D,fe={name:"@genie/agent-harness",title:"Agent Harness",version:R},he=(f.preflightCodeBuddyCode??vr)(),L=new kr,B=new AbortController,y=Gr(ue),q=k(()=>jr(y,g,Math.max(1,Math.min(D.remainingMs(),ue.flushTimeoutMs??Kr))));D.registerTelemetryCloser(q);const ge=qr(e=>y.recordEffectMetrics(e));try{w(q)}catch(e){throw await q(),e}try{g.setTelemetryObserver({log:t(e=>y.recordEffectLog(e),"log"),metrics:t(e=>ge.record("harness",e),"metrics"),span:t(e=>y.recordEffectSpan(e),"span")})}catch{}const M=t(e=>y.recordLifecycle(e),"recordLifecycle"),z=new Rr(process.env.CODEBUDDY_CONFIG_DIR?.trim()?I.resolve(process.env.CODEBUDDY_CONFIG_DIR.trim()):I.join(Le(),".codebuddy"),Ge,process.env.SANDBOX_CENTER_IPC_ADDRESS?.trim()),G=k(()=>z.close());w(G);let ye=!1;const j=t((e,i,U)=>{ye||(ye=!0,M({component:"server",error:e,phase:"runtime",process:{pid:process.pid},reason:U,state:i}))},"recordRootFailure");L.signal.addEventListener("abort",()=>{j(L.signal.reason,"containment_tripped","containment_failed")},{once:!0});const Xe={log(e){try{y.recordEffectLog(e)}catch{}},metrics(e){ge.record("executor",e)},span(e){try{y.recordEffectSpan(e)}catch{}}};let A,n,N,T,c,_,x,E;const ve=d.get(await C(Ue.layer(je??(()=>{})),pe),Ue),O=m.makeUnsafe(),K=k(e=>a.runPromise(m.close(O,e===void 0?h.void:h.fail(e))));w(()=>K(void 0));const V=t(()=>{N&&a.runPromise(a.forkIn(N.prepare,O,{startImmediately:!0})).catch(()=>{})},"prepareRuntime"),Ee=m.makeUnsafe(),X=k(async e=>{try{await c?.close(e)}finally{await a.runPromise(m.close(Ee,e===void 0?h.void:h.fail(e)))}});w(()=>X(void 0));const Q=m.makeUnsafe(),J=k(e=>a.runPromise(m.close(Q,e===void 0?h.void:h.fail(e))));w(()=>J(void 0));const Se=m.makeUnsafe(),Z=k(e=>a.runPromise(m.close(Se,e===void 0?h.void:h.fail(e))));w(()=>Z(void 0));const Pe=m.makeUnsafe(),$=k(async e=>{try{await n?.close(e)}finally{await a.runPromise(m.close(Pe,e===void 0?h.void:h.fail(e)))}});w(()=>$(void 0));try{const e={...process.env},i={...P,...z.environment},U=typeof b=="object"?br(b):Ir(b,{parse:_r});u?.throwIfAborted(),s()?.markStart("harness.product");const Qe=await C(Be.layer({projection:U.projection,baseConfiguration:b===void 0?void 0:{},packageRoot:he.productRoot??I.dirname(he.packageJsonPath),clientIdentity:{ideName:l.ideName,ideType:l.ideType,ideVersion:l.ideVersion,...l.userAgent===void 0?{}:{userAgent:l.userAgent}},environment:t(()=>({...e,...i}),"environment")}),Ee);c=await(f.createProductManager??((r,o)=>Dr.create(r,o)))({bootstrap:U.bootstrap,projection:U.projection,resolver:d.get(Qe,Be)},u),s()?.markEnd("harness.product");const Je=t(()=>{if(!c)throw new Error("Product manager is not ready");return c.getLaunchSnapshot()},"productLaunch");u?.throwIfAborted(),s()?.markStart("harness.config");const Ze=await C(ae.layer.pipe(p.provide(F)),Q);s()?.markEnd("harness.config");const re=d.get(Ze,ae),Ae=t((r,o)=>Hr(re,r,o),"sessionConfigDefaults");u?.throwIfAborted(),s()?.markStart("harness.settings"),_=await(f.createSettingsRuntime??Nr)({ambientEnvironment:e,config:re,environment:i,observe:t(r=>y.recordEffectLog({annotations:{component:"harness",operation:"refresh",reason:r.reason,resource:"policy","runtime.role":"harness",status:r.status,...r.policy===void 0?{}:{mode:r.policy.mode,noProxyCount:r.policy.noProxyCount,proxyConfigured:r.policy.proxyConfigured,proxySupport:r.policy.proxySupport,revision:r.policy.revision}},level:r.status==="failed"?"warn":"info",message:"harness.settings.proxy"}),"observe"),processRuntime:g}),s()?.markEnd("harness.settings");const ke=Fr.layer(I.join(e.CODEBUDDY_CONFIG_DIR?.trim()?I.resolve(e.CODEBUDDY_CONFIG_DIR.trim()):I.join(Le(),".codebuddy"),"harness","sessions"));u?.throwIfAborted(),s()?.markStart("harness.session-runtime");const _e=process.platform==="linux"?e[xe]??((await import("#agent-harness-components/session-config")).isLinuxSandboxCLIInstalled()?"1":"0"):void 0,be=await C(f.sessionRuntimeLayer??Or({checkpoints:!0,headers:Sr(l),prepareSandboxCenter:t((r,o)=>z.prepare(r.account?.uid,o),"prepareSandboxCenter"),resolveOptions:t(r=>a.map(Ur(r),o=>({...o,...de===void 0?{}:{tools:de},...ve===void 0?{}:{mods:ve.bridge}})),"resolveOptions"),resolveConfigDefaults:t(r=>a.tryPromise({try:t(()=>Ae(r.workspace?.canonicalCwd??r.cwd??process.cwd(),r.signal),"try"),catch:t(o=>o,"catch")}),"resolveConfigDefaults")}).pipe(p.provideMerge(ze.layer({product:{},fs:Ne,settingSources:["user","project","local"],env:{...Er(l),CODEBUDDY_API_KEY_DISABLED:"1",CODEBUDDY_REMOTE_CONFIG_DISABLED:"1",CODEBUDDY_INCLUDE_TOPIC_MESSAGE:"true",..._e===void 0?{}:{[xe]:_e},...z.environment,CODEBUDDY_CODE_DISABLE_FILE_CHECKPOINTING:e.CODEBUDDY_CODE_DISABLE_FILE_CHECKPOINTING??"0"}})),p.provide(ke)),O);s()?.markEnd("harness.session-runtime"),N=d.get(be,zr),u?.throwIfAborted(),s()?.markStart("harness.replay");const $e=d.get(await C(We.layer({},r=>Ne.readFileBuffer(r),Ae).pipe(p.provide(ke)),O),We);s()?.markEnd("harness.replay"),u?.throwIfAborted(),s()?.markStart("harness.storage");const De=await C(p.mergeAll(Ye.layer,Oe.layer).pipe(p.provide(Br.layer),p.provide(F)),O);s()?.markEnd("harness.storage");const er=d.get(De,Ye),rr=d.get(De,Oe);T=(f.createMcpIntegration??(r=>lr({containment:r.containment,recordEffectTelemetry:r.recordEffectTelemetry,recordLifecycle:r.recordLifecycle,supervisor:{environment:r.environment,toolsSyncTtlMs:Ve?.toolsSyncTtlMs,proxyPolicy:r.proxyPolicy}})))({containment:L,environment:i,proxyPolicy:qe(_.currentProxyPolicy,i),recordEffectTelemetry:Xe,recordLifecycle:M}),x=_.subscribe(r=>{const o=qe(r,i);T?.configureProxy?.(o).catch(()=>{y.recordEffectLog({annotations:{component:"harness",operation:"update",resource:"policy","runtime.role":"harness",status:"failed"},level:"warn",message:"harness.settings.proxy"})})});const Me=sr.getOrUndefined(d.getOption(be,ze));u?.throwIfAborted(),s()?.markStart("harness.mcp-services");const te=await C(p.mergeAll(Fe.layer({environment:t(()=>({...e,...i}),"environment")}),He.layer).pipe(p.provideMerge(se.layer({environment:t(()=>({...e,...i}),"environment"),product:t(()=>c.getConfiguration(),"product"),writeContext:t(async()=>{await n?.prepareHostExecution(B.signal);const r=t(()=>({environment:{...e,...i},product:structuredClone(c.getConfiguration()),authentication:n?.currentSessionAuthentication()}),"capture");return n?n.runConsistentRead(r):r()},"writeContext"),onConfigChange:Me?async(r,o)=>{const v=o.authentication;Me.notifyConfigChange({source:r.source,filePath:r.file_path,cwd:r.cwd},{product:o.product,environment:o.environment,fetch:t((ne,W)=>fr(ne,W,o.environment),"fetch"),auth:v?{accessToken:v.credential.accessToken,method:v.credential.type,refresh:t(async({signal:ne})=>{if(!n||!c)throw new Error("Hook authentication is unavailable");const W=t(()=>{if(!ar(o.product,c.getConfiguration()))throw new Error("Hook Product changed")},"checkProduct");await n.runConsistentRead(W);const Re=await n.refreshHostAuthentication(v,ne);return await n.runConsistentRead(W),{accessToken:Re.credential.accessToken,method:Re.credential.type}},"refresh")}:void 0,account:v?{uid:v.account.id,enterpriseId:v.account.organization?.id}:void 0}).catch(()=>a.runSync(a.logWarning("harness.config-change.failed").pipe(a.provide(F))))}:void 0,reloadUserConfig:t(r=>A?.reloadUserConfig(r)??Promise.resolve(),"reloadUserConfig")})),p.provide(F)),Se);s()?.markEnd("harness.mcp-services"),u?.throwIfAborted(),s()?.markStart("harness.agent-facade"),A=await(f.createAgentFacade??dr)({userMcp:d.get(te,Fe),pluginMcp:d.get(te,He),checkpoints:rr,sessions:er,initialProductGeneration:Je().productGeneration,mcpIntegration:T,strictMcpConfig:Ke,onPermanentFailure:t(r=>{j(r,"fused","recovery_failed"),B.abort(r)},"onPermanentFailure"),prepareSessionRuntime:t((r,o)=>{if(!n)throw new Error("Authentication runtime is not ready");return n.prepareSessionRuntime(r,o.connectionSignal)},"prepareSessionRuntime"),prepareSessionWorkspace:t(async(r,o)=>{if(!n||!c)throw new Error("Product manager is not ready");try{return await c.prepareWorkspace(r,{signal:o})}catch(v){if(!(v instanceof Mr&&v.code==="AUTH_REFRESH_REQUIRED"))throw v;return await n.refreshProductAuthentication(o),c.prepareWorkspace(r,{force:!0,signal:o})}},"prepareSessionWorkspace"),releaseSessionWorkspace:t((r,o)=>c?c.releaseWorkspace(r,o):Promise.resolve(),"releaseSessionWorkspace"),refreshAuthentication:t((r,o)=>{if(!n)throw new Error("Authentication runtime is not ready");return n.refreshAuthentication(r,{signal:o?.signal??AbortSignal.abort(new Error("Authentication refresh has no operation signal"))})},"refreshAuthentication"),serverInfo:fe,sessionRuntime:N,sessionReplay:$e}),s()?.markEnd("harness.agent-facade");const Ie=Cr({facade:A,onExecutionProductCommitted:V,product:c});u?.throwIfAborted(),s()?.markStart("harness.auth-service");const tr=await C(f.managedAuthLayer??ur({...c.resolveLoginProduct?{resolveLoginProduct:t((r,o)=>c.resolveLoginProduct(r,o),"resolveLoginProduct")}:{},environment:t(()=>({...e,...i}),"environment"),product:t(()=>c.getConfiguration(),"product")}).pipe(p.provide(F)),Pe);s()?.markEnd("harness.auth-service"),n=Pr({consumer:A,getAuthMethods:t(()=>c.getAuthMethods(),"getAuthMethods"),managedAuth:d.get(tr,pr),onRuntimePreparing:V,onRuntimePrepared:V,productLifecycle:Ie});const S=await mr(n);n.bindProtocolBridge(S.bridge);const oe=yr({selectConnectionProductProfile:t((r,o)=>n.selectConnectionProductProfile(r,o),"selectConnectionProductProfile"),provisionProduct:t((r,o)=>S.runAuthMutation(()=>n.provisionProduct(r,o),{signal:o.signal}),"provisionProduct"),readProduct:t((r,o)=>n.readProduct(r,o),"readProduct"),provisionWorkspaceProduct:t((r,o)=>S.runAuthMutation(()=>n.provisionWorkspaceProduct(r,o),{signal:o.signal}),"provisionWorkspaceProduct"),readWorkspaceProduct:t((r,o)=>c.readWorkspaceProduct(r,o),"readWorkspaceProduct")});c.bindPublisher({notifyProductUpdated:t(()=>oe.publisher.notifyProductUpdated(Ie.currentProductSnapshot()),"notifyProductUpdated"),notifyWorkspaceProductUpdated:t(r=>oe.publisher.notifyWorkspaceProductUpdated(r),"notifyWorkspaceProductUpdated")});const or=d.empty().pipe(d.add(Wr,_),d.add(ae,re),d.add(se,d.get(te,se)));u?.throwIfAborted(),s()?.markStart("harness.rpc-services");const nr=await le(a.provide(xr.pipe(m.provide(Q),a.provideService(p.CurrentMemoMap,me)),or));s()?.markEnd("harness.rpc-services"),E=gr([{name:"private-runtime-lifecycle",capabilities:{},initialize:t(async(r,o)=>{await ce("harness.initialize.settings",()=>_?.initialize(o.connectionSignal))},"initialize"),close:t(async r=>{x?.(),x=void 0,await Z(r),await _?.close(r),await H([[()=>K(r),()=>T?.close(r)??Promise.resolve()],[()=>G()],[()=>X(r)]],Y,"private runtime shutdown")},"close")},cr({v2:A}),hr({backend:A}),Yr({backend:A}),oe,{name:S.name,capabilities:S.capabilities,initialize:t(async(r,o)=>ce("harness.initialize.auth",()=>S.initialize(r,o)),"initialize"),initialized:S.initialized,notificationHandlers:S.notificationHandlers,requestHandlers:S.requestHandlers,close:$},{...nr,close:J}])}catch(e){throw x?.(),x=void 0,M({component:"server",error:e,phase:"startup",process:{pid:process.pid},reason:"startup_failed",state:"startup_failed"}),await H([[()=>J(e)],[()=>$(e)],[()=>A?.close(e)??Promise.resolve(),()=>K(e)],[()=>T?.close(e)??Promise.resolve()],[()=>Z(e)],[()=>_?.close(e)??Promise.resolve()],[()=>G()],[()=>X(e)]],Y,"module startup cleanup").catch(()=>{}),e}let ee;try{u?.throwIfAborted(),ee=(f.createServer??(e=>new Lr(e)))({serverInfo:fe,capabilities:E.capabilities,initializeHookTimeoutMs:Ar+wr+Tr,initialize:t(async(e,i)=>(s()?.markEnd("harness.wait-initialize"),ce("harness.initialize",()=>E.initialize(e,i))),"initialize"),initialized:E.initialized,notificationHandlers:E.notificationHandlers,onContainmentFailure:t(e=>{j(e,"containment_tripped","containment_failed"),B.abort(e)},"onContainmentFailure"),readinessSignal:L.signal,requestHandlers:E.requestHandlers,telemetryRuntime:y})}catch(e){M({component:"server",error:e,phase:"startup",process:{pid:process.pid},reason:"startup_failed",state:"startup_failed"});try{await H([[()=>E.close(e)]],Y,"server construction cleanup")}catch(i){M({component:"server",error:i,phase:"cleanup",process:{pid:process.pid},reason:"cleanup_failed",state:"shutdown_failed"})}throw e}let Ce;const we=t(e=>Ce??=H([[()=>ee.close(e),()=>E.close(e)]],D,"application services shutdown"),"close");return w(()=>Ce?Promise.resolve():we()),{server:ee,modules:E,telemetry:y,containment:L,runtimeShutdown:B,recordLifecycle:M,close:we}}t(Xr,"acquireApplicationServices");
|
|
1
|
+
var ar=Object.defineProperty;var t=(l,P)=>ar(l,"name",{value:P,configurable:!0});import{homedir as Le}from"node:os";import*as I from"node:path";import{isDeepStrictEqual as sr}from"node:util";import{Cause as Te,Context as d,Effect as a,Exit as h,Layer as p,Logger as ie,Option as cr,Scope as m}from"effect";import{WORKBUDDY_ENABLE_LINUX_SANDBOX_CLI as xe}from"#agent-harness-components/sandbox";import{createAgentProtocolModule as dr}from"../agent/router.js";import{createAgentV2Facade as ur}from"../agent/v2.js";import{ManagedAuthLocal as pr}from"../auth/local.js";import{ManagedAuth as mr}from"../auth/managed.js";import{createAuthProtocolModule as lr}from"../auth/module.js";import{Checkpoints as Oe}from"../checkpoint/service.js";import{ConfigFiles as ae}from"../config/files.js";import{HostHooks as Ue}from"../harness/hooks.js";import{createDefaultAgentMcpIntegration as fr}from"../integration/agent-integration.js";import{PluginMcp as He}from"../integration/plugin-mcp.js";import{UserMcp as Fe}from"../integration/user-mcp.js";import{requestWithEnvironment as hr}from"../internal/http.js";import{createMcpServerProtocolModule as gr}from"../mcp-server/module.js";import{composeAgentHarnessModules as yr}from"../module/compose.js";import{PluginComponents as se}from"../plugin/components.js";import{createProductProtocolModule as vr}from"../product/module.js";import{preflightCodeBuddyCode as Er}from"../runtime/agent-runtime.js";import{buildAgentHarnessClientIdentityEnv as Sr,buildAgentHarnessClientIdentityHeaders as Pr}from"../runtime/client-identity.js";import{createCodeBuddyAuthRuntime as Cr}from"../runtime/codebuddy-auth.js";import{createCodeBuddyProductLifecycle as wr}from"../runtime/codebuddy-product.js";import{DEFAULT_HOST_HEALTH_TIMEOUT_MS as Ar,DEFAULT_READY_TIMEOUT_MS as kr}from"../runtime/codebuddy-resource-timeouts.js";import{CodeBuddyProcessContainment as _r}from"../runtime/process-containment.js";import{parseAgentHarnessProductConfig as br,parseHarnessProductInput as Dr}from"../runtime/product-config.js";import{ProductManager as Mr}from"../runtime/product-manager.js";import{ProductResolver as Be}from"../runtime/product-resolver.js";import{ProductResolverRequestError as Ir}from"../runtime/product-resolver-error.js";import{loadProductSource as Rr}from"../runtime/product-source.js";import{HarnessSandboxCenter as Lr}from"../runtime/sandbox-center.js";import{AgentHarnessServer as Tr,DEFAULT_LIFECYCLE_HOOK_TIMEOUT_MS as xr}from"../server/index.js";import{makeServiceRpcs as Or}from"../server/rpc-services.js";import{AgentBackend as Ur,workspaceQueryOptions as Hr}from"../session/agent-backend.js";import{AgentServer as ze}from"../session/agent-server.js";import{readSessionConfigDefaults as Fr}from"../session/config-defaults.js";import{SessionConfigStore as Br}from"../session/config-store.js";import{SessionFiles as zr}from"../session/files.js";import{localFs as Ne}from"../session/local-fs.js";import{SessionReplay as We}from"../session/replay.js";import{SessionRuntime as Nr}from"../session/runtime.js";import{Sessions as Ye}from"../session/service.js";import{toExecutorPrivateProxyPolicy as qe}from"../settings/proxy-policy.js";import{createHarnessSettingsRuntime as Wr}from"../settings/runtime.js";import{Settings as Yr}from"../settings/service.js";import{createSubagentProtocolModule as qr}from"../subagent/module.js";import{createEffectTelemetryMetricAggregator as Gr}from"../telemetry/effect-metric-aggregation.js";import{createTelemetry as jr}from"../telemetry/runtime.js";import{measureStartup as ce,startupProfiler as s}from"../telemetry/startup-profile.js";import{closeInPhases as H,closeTelemetry as Kr,createCloseOnce as k,DEFAULT_TELEMETRY_CLOSE_TIMEOUT_MS as Vr,withNativeShutdownTimeout as Xr}from"./lifecycle.js";const F=ie.layer([ie.withConsoleError(ie.formatLogFmt)]);export class Application extends d.Service()("@genie/agent-harness/application/Application"){static{t(this,"Application")}static layer(P){return p.fromBuildMemo((f,R)=>a.gen(function*(){const g=yield*a.tryPromise({try:t(()=>Qr(P,R,f),"try"),catch:t(b=>b,"catch")});return d.make(Application,g)}).pipe(a.uninterruptible))}}export async function createApplicationServices(l){const P=m.makeUnsafe(),f=k(g=>a.runPromise(m.close(P,g===void 0?h.void:h.fail(g)))),R=l.processRuntime.addFinalizer(()=>f());try{return d.get(await a.runPromise(p.buildWithScope(Application.layer(l),P)),Application)}catch(g){throw await H([[()=>f(g)]],l.shutdown,"application acquisition cleanup").then(R,()=>{}),g}}t(createApplicationServices,"createApplicationServices");async function Qr({clientIdentity:l,clientIdentityEnv:P,dependencies:f,packageVersion:R,processRuntime:g,productConfig:b,sandboxCenter:Ge,tools:de,hooks:je,strictMcpConfig:Ke,maxActiveSessions:Ve,mcp:Xe,shutdown:D,telemetryOptions:ue,signal:u},pe,me){u?.throwIfAborted();const le=t(async e=>{const i=await a.runPromiseExit(e,{signal:u});if(h.isSuccess(i))return i.value;throw u?.aborted&&Te.hasInterruptsOnly(i.cause)?u.reason:Te.squash(i.cause)},"runStartupEffect"),C=t((e,i)=>le(p.buildWithMemoMap(e,me,i)),"build"),w=t(e=>a.runSync(m.addFinalizerExit(pe,()=>a.promise(()=>Xr(Promise.resolve().then(e),Math.max(1,Math.min(D.phaseMs,D.remainingMs())),"application resource release")))),"addFinalizer"),Y=D,fe={name:"@genie/agent-harness",title:"Agent Harness",version:R},he=(f.preflightCodeBuddyCode??Er)(),L=new _r,B=new AbortController,y=jr(ue),q=k(()=>Kr(y,g,Math.max(1,Math.min(D.remainingMs(),ue.flushTimeoutMs??Vr))));D.registerTelemetryCloser(q);const ge=Gr(e=>y.recordEffectMetrics(e));try{w(q)}catch(e){throw await q(),e}try{g.setTelemetryObserver({log:t(e=>y.recordEffectLog(e),"log"),metrics:t(e=>ge.record("harness",e),"metrics"),span:t(e=>y.recordEffectSpan(e),"span")})}catch{}const M=t(e=>y.recordLifecycle(e),"recordLifecycle"),z=new Lr(process.env.CODEBUDDY_CONFIG_DIR?.trim()?I.resolve(process.env.CODEBUDDY_CONFIG_DIR.trim()):I.join(Le(),".codebuddy"),Ge,process.env.SANDBOX_CENTER_IPC_ADDRESS?.trim()),G=k(()=>z.close());w(G);let ye=!1;const j=t((e,i,U)=>{ye||(ye=!0,M({component:"server",error:e,phase:"runtime",process:{pid:process.pid},reason:U,state:i}))},"recordRootFailure");L.signal.addEventListener("abort",()=>{j(L.signal.reason,"containment_tripped","containment_failed")},{once:!0});const Qe={log(e){try{y.recordEffectLog(e)}catch{}},metrics(e){ge.record("executor",e)},span(e){try{y.recordEffectSpan(e)}catch{}}};let A,n,N,T,c,_,x,E;const ve=d.get(await C(Ue.layer(je??(()=>{})),pe),Ue),O=m.makeUnsafe(),K=k(e=>a.runPromise(m.close(O,e===void 0?h.void:h.fail(e))));w(()=>K(void 0));const V=t(()=>{N&&a.runPromise(a.forkIn(N.prepare,O,{startImmediately:!0})).catch(()=>{})},"prepareRuntime"),Ee=m.makeUnsafe(),X=k(async e=>{try{await c?.close(e)}finally{await a.runPromise(m.close(Ee,e===void 0?h.void:h.fail(e)))}});w(()=>X(void 0));const Q=m.makeUnsafe(),J=k(e=>a.runPromise(m.close(Q,e===void 0?h.void:h.fail(e))));w(()=>J(void 0));const Se=m.makeUnsafe(),Z=k(e=>a.runPromise(m.close(Se,e===void 0?h.void:h.fail(e))));w(()=>Z(void 0));const Pe=m.makeUnsafe(),$=k(async e=>{try{await n?.close(e)}finally{await a.runPromise(m.close(Pe,e===void 0?h.void:h.fail(e)))}});w(()=>$(void 0));try{const e={...process.env},i={...P,...z.environment},U=typeof b=="object"?Dr(b):Rr(b,{parse:br});u?.throwIfAborted(),s()?.markStart("harness.product");const Je=await C(Be.layer({projection:U.projection,baseConfiguration:b===void 0?void 0:{},packageRoot:he.productRoot??I.dirname(he.packageJsonPath),clientIdentity:{ideName:l.ideName,ideType:l.ideType,ideVersion:l.ideVersion,...l.userAgent===void 0?{}:{userAgent:l.userAgent}},environment:t(()=>({...e,...i}),"environment")}),Ee);c=await(f.createProductManager??((r,o)=>Mr.create(r,o)))({bootstrap:U.bootstrap,projection:U.projection,resolver:d.get(Je,Be)},u),s()?.markEnd("harness.product");const Ze=t(()=>{if(!c)throw new Error("Product manager is not ready");return c.getLaunchSnapshot()},"productLaunch");u?.throwIfAborted(),s()?.markStart("harness.config");const $e=await C(ae.layer.pipe(p.provide(F)),Q);s()?.markEnd("harness.config");const re=d.get($e,ae),Ae=t((r,o)=>Fr(re,r,o),"sessionConfigDefaults");u?.throwIfAborted(),s()?.markStart("harness.settings"),_=await(f.createSettingsRuntime??Wr)({ambientEnvironment:e,config:re,environment:i,observe:t(r=>y.recordEffectLog({annotations:{component:"harness",operation:"refresh",reason:r.reason,resource:"policy","runtime.role":"harness",status:r.status,...r.policy===void 0?{}:{mode:r.policy.mode,noProxyCount:r.policy.noProxyCount,proxyConfigured:r.policy.proxyConfigured,proxySupport:r.policy.proxySupport,revision:r.policy.revision}},level:r.status==="failed"?"warn":"info",message:"harness.settings.proxy"}),"observe"),processRuntime:g}),s()?.markEnd("harness.settings");const ke=Br.layer(I.join(e.CODEBUDDY_CONFIG_DIR?.trim()?I.resolve(e.CODEBUDDY_CONFIG_DIR.trim()):I.join(Le(),".codebuddy"),"harness","sessions"));u?.throwIfAborted(),s()?.markStart("harness.session-runtime");const _e=process.platform==="linux"?e[xe]??((await import("#agent-harness-components/session-config")).isLinuxSandboxCLIInstalled()?"1":"0"):void 0,be=await C(f.sessionRuntimeLayer??Ur({checkpoints:!0,headers:Pr(l),prepareSandboxCenter:t((r,o)=>z.prepare(r.account?.uid,o),"prepareSandboxCenter"),resolveOptions:t(r=>a.map(Hr(r),o=>({...o,...de===void 0?{}:{tools:de},...ve===void 0?{}:{mods:ve.bridge}})),"resolveOptions"),resolveConfigDefaults:t(r=>a.tryPromise({try:t(()=>Ae(r.workspace?.canonicalCwd??r.cwd??process.cwd(),r.signal),"try"),catch:t(o=>o,"catch")}),"resolveConfigDefaults")}).pipe(p.provideMerge(ze.layer({product:{},fs:Ne,settingSources:["user","project","local"],env:{...Sr(l),CODEBUDDY_API_KEY_DISABLED:"1",CODEBUDDY_REMOTE_CONFIG_DISABLED:"1",CODEBUDDY_INCLUDE_TOPIC_MESSAGE:"true",..._e===void 0?{}:{[xe]:_e},...z.environment,CODEBUDDY_CODE_DISABLE_FILE_CHECKPOINTING:e.CODEBUDDY_CODE_DISABLE_FILE_CHECKPOINTING??"0"}})),p.provide(ke)),O);s()?.markEnd("harness.session-runtime"),N=d.get(be,Nr),u?.throwIfAborted(),s()?.markStart("harness.replay");const er=d.get(await C(We.layer({},r=>Ne.readFileBuffer(r),Ae).pipe(p.provide(ke)),O),We);s()?.markEnd("harness.replay"),u?.throwIfAborted(),s()?.markStart("harness.storage");const De=await C(p.mergeAll(Ye.layer,Oe.layer).pipe(p.provide(zr.layer),p.provide(F)),O);s()?.markEnd("harness.storage");const rr=d.get(De,Ye),tr=d.get(De,Oe);T=(f.createMcpIntegration??(r=>fr({containment:r.containment,recordEffectTelemetry:r.recordEffectTelemetry,recordLifecycle:r.recordLifecycle,supervisor:{environment:r.environment,toolsSyncTtlMs:Xe?.toolsSyncTtlMs,proxyPolicy:r.proxyPolicy}})))({containment:L,environment:i,proxyPolicy:qe(_.currentProxyPolicy,i),recordEffectTelemetry:Qe,recordLifecycle:M}),x=_.subscribe(r=>{const o=qe(r,i);T?.configureProxy?.(o).catch(()=>{y.recordEffectLog({annotations:{component:"harness",operation:"update",resource:"policy","runtime.role":"harness",status:"failed"},level:"warn",message:"harness.settings.proxy"})})});const Me=cr.getOrUndefined(d.getOption(be,ze));u?.throwIfAborted(),s()?.markStart("harness.mcp-services");const te=await C(p.mergeAll(Fe.layer({environment:t(()=>({...e,...i}),"environment")}),He.layer).pipe(p.provideMerge(se.layer({environment:t(()=>({...e,...i}),"environment"),product:t(()=>c.getConfiguration(),"product"),writeContext:t(async()=>{await n?.prepareHostExecution(B.signal);const r=t(()=>({environment:{...e,...i},product:structuredClone(c.getConfiguration()),authentication:n?.currentSessionAuthentication()}),"capture");return n?n.runConsistentRead(r):r()},"writeContext"),onConfigChange:Me?async(r,o)=>{const v=o.authentication;Me.notifyConfigChange({source:r.source,filePath:r.file_path,cwd:r.cwd},{product:o.product,environment:o.environment,fetch:t((ne,W)=>hr(ne,W,o.environment),"fetch"),auth:v?{accessToken:v.credential.accessToken,method:v.credential.type,refresh:t(async({signal:ne})=>{if(!n||!c)throw new Error("Hook authentication is unavailable");const W=t(()=>{if(!sr(o.product,c.getConfiguration()))throw new Error("Hook Product changed")},"checkProduct");await n.runConsistentRead(W);const Re=await n.refreshHostAuthentication(v,ne);return await n.runConsistentRead(W),{accessToken:Re.credential.accessToken,method:Re.credential.type}},"refresh")}:void 0,account:v?{uid:v.account.id,enterpriseId:v.account.organization?.id}:void 0}).catch(()=>a.runSync(a.logWarning("harness.config-change.failed").pipe(a.provide(F))))}:void 0,reloadUserConfig:t(r=>A?.reloadUserConfig(r)??Promise.resolve(),"reloadUserConfig")})),p.provide(F)),Se);s()?.markEnd("harness.mcp-services"),u?.throwIfAborted(),s()?.markStart("harness.agent-facade"),A=await(f.createAgentFacade??ur)({userMcp:d.get(te,Fe),pluginMcp:d.get(te,He),checkpoints:tr,sessions:rr,initialProductGeneration:Ze().productGeneration,mcpIntegration:T,strictMcpConfig:Ke,maxActiveSessions:Ve,onPermanentFailure:t(r=>{j(r,"fused","recovery_failed"),B.abort(r)},"onPermanentFailure"),prepareSessionRuntime:t((r,o)=>{if(!n)throw new Error("Authentication runtime is not ready");return n.prepareSessionRuntime(r,o.connectionSignal)},"prepareSessionRuntime"),prepareSessionWorkspace:t(async(r,o)=>{if(!n||!c)throw new Error("Product manager is not ready");try{return await c.prepareWorkspace(r,{signal:o})}catch(v){if(!(v instanceof Ir&&v.code==="AUTH_REFRESH_REQUIRED"))throw v;return await n.refreshProductAuthentication(o),c.prepareWorkspace(r,{force:!0,signal:o})}},"prepareSessionWorkspace"),releaseSessionWorkspace:t((r,o)=>c?c.releaseWorkspace(r,o):Promise.resolve(),"releaseSessionWorkspace"),refreshAuthentication:t((r,o)=>{if(!n)throw new Error("Authentication runtime is not ready");return n.refreshAuthentication(r,{signal:o?.signal??AbortSignal.abort(new Error("Authentication refresh has no operation signal"))})},"refreshAuthentication"),serverInfo:fe,sessionRuntime:N,sessionReplay:er}),s()?.markEnd("harness.agent-facade");const Ie=wr({facade:A,onExecutionProductCommitted:V,product:c});u?.throwIfAborted(),s()?.markStart("harness.auth-service");const or=await C(f.managedAuthLayer??pr({...c.resolveLoginProduct?{resolveLoginProduct:t((r,o)=>c.resolveLoginProduct(r,o),"resolveLoginProduct")}:{},environment:t(()=>({...e,...i}),"environment"),product:t(()=>c.getConfiguration(),"product")}).pipe(p.provide(F)),Pe);s()?.markEnd("harness.auth-service"),n=Cr({consumer:A,getAuthMethods:t(()=>c.getAuthMethods(),"getAuthMethods"),managedAuth:d.get(or,mr),onRuntimePreparing:V,onRuntimePrepared:V,productLifecycle:Ie});const S=await lr(n);n.bindProtocolBridge(S.bridge);const oe=vr({selectConnectionProductProfile:t((r,o)=>n.selectConnectionProductProfile(r,o),"selectConnectionProductProfile"),provisionProduct:t((r,o)=>S.runAuthMutation(()=>n.provisionProduct(r,o),{signal:o.signal}),"provisionProduct"),readProduct:t((r,o)=>n.readProduct(r,o),"readProduct"),provisionWorkspaceProduct:t((r,o)=>S.runAuthMutation(()=>n.provisionWorkspaceProduct(r,o),{signal:o.signal}),"provisionWorkspaceProduct"),readWorkspaceProduct:t((r,o)=>c.readWorkspaceProduct(r,o),"readWorkspaceProduct")});c.bindPublisher({notifyProductUpdated:t(()=>oe.publisher.notifyProductUpdated(Ie.currentProductSnapshot()),"notifyProductUpdated"),notifyWorkspaceProductUpdated:t(r=>oe.publisher.notifyWorkspaceProductUpdated(r),"notifyWorkspaceProductUpdated")});const nr=d.empty().pipe(d.add(Yr,_),d.add(ae,re),d.add(se,d.get(te,se)));u?.throwIfAborted(),s()?.markStart("harness.rpc-services");const ir=await le(a.provide(Or.pipe(m.provide(Q),a.provideService(p.CurrentMemoMap,me)),nr));s()?.markEnd("harness.rpc-services"),E=yr([{name:"private-runtime-lifecycle",capabilities:{},initialize:t(async(r,o)=>{await ce("harness.initialize.settings",()=>_?.initialize(o.connectionSignal))},"initialize"),close:t(async r=>{x?.(),x=void 0,await Z(r),await _?.close(r),await H([[()=>K(r),()=>T?.close(r)??Promise.resolve()],[()=>G()],[()=>X(r)]],Y,"private runtime shutdown")},"close")},dr({v2:A}),gr({backend:A}),qr({backend:A}),oe,{name:S.name,capabilities:S.capabilities,initialize:t(async(r,o)=>ce("harness.initialize.auth",()=>S.initialize(r,o)),"initialize"),initialized:S.initialized,notificationHandlers:S.notificationHandlers,requestHandlers:S.requestHandlers,close:$},{...ir,close:J}])}catch(e){throw x?.(),x=void 0,M({component:"server",error:e,phase:"startup",process:{pid:process.pid},reason:"startup_failed",state:"startup_failed"}),await H([[()=>J(e)],[()=>$(e)],[()=>A?.close(e)??Promise.resolve(),()=>K(e)],[()=>T?.close(e)??Promise.resolve()],[()=>Z(e)],[()=>_?.close(e)??Promise.resolve()],[()=>G()],[()=>X(e)]],Y,"module startup cleanup").catch(()=>{}),e}let ee;try{u?.throwIfAborted(),ee=(f.createServer??(e=>new Tr(e)))({serverInfo:fe,capabilities:E.capabilities,initializeHookTimeoutMs:kr+Ar+xr,initialize:t(async(e,i)=>(s()?.markEnd("harness.wait-initialize"),ce("harness.initialize",()=>E.initialize(e,i))),"initialize"),initialized:E.initialized,notificationHandlers:E.notificationHandlers,onContainmentFailure:t(e=>{j(e,"containment_tripped","containment_failed"),B.abort(e)},"onContainmentFailure"),readinessSignal:L.signal,requestHandlers:E.requestHandlers,telemetryRuntime:y})}catch(e){M({component:"server",error:e,phase:"startup",process:{pid:process.pid},reason:"startup_failed",state:"startup_failed"});try{await H([[()=>E.close(e)]],Y,"server construction cleanup")}catch(i){M({component:"server",error:i,phase:"cleanup",process:{pid:process.pid},reason:"cleanup_failed",state:"shutdown_failed"})}throw e}let Ce;const we=t(e=>Ce??=H([[()=>ee.close(e),()=>E.close(e)]],D,"application services shutdown"),"close");return w(()=>Ce?Promise.resolve():we()),{server:ee,modules:E,telemetry:y,containment:L,runtimeShutdown:B,recordLifecycle:M,close:we}}t(Qr,"acquireApplicationServices");
|
package/lib/cli/main.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var M=Object.defineProperty;var c=(e,t)=>M(e,"name",{value:t,configurable:!0});import{readFileSync as
|
|
2
|
-
`),"onWarning")})}catch(l){throw await k(l).catch(()=>{}),w({component:"server",error:l,phase:"startup",process:{pid:process.pid},reason:"startup_failed",state:"startup_failed"}),l}
|
|
3
|
-
`);const T=F(()=>A.close());w({component:"server",phase:"startup",process:{pid:process.pid},reason:"startup_completed",state:"started"}),await _(A.closed,l=>P(H,()=>
|
|
1
|
+
var M=Object.defineProperty;var c=(e,t)=>M(e,"name",{value:t,configurable:!0});import{readFileSync as $}from"node:fs";import{homedir as N}from"node:os";import*as y from"node:path";import{closeAll as B,closeHarnessProcessRuntime as I,closeInPhases as J,closeWithLifecycleTelemetry as P,createCloseOnce as F,resolveShutdownCoordinator as V,runUntilClosed as _,withNativeShutdownTimeout as j}from"../application/lifecycle.js";import{createApplicationServices as W}from"../application/services.js";import{buildAgentHarnessClientIdentityEnv as z,resolveAgentHarnessClientIdentity as U}from"../runtime/client-identity.js";import{createDailyJsonlFileSink as Y}from"../telemetry/daily-jsonl-file-sink.js";import{startupProfiler as L}from"../telemetry/startup-profile.js";import{createBearerTokenAuthenticator as q,createSignedBearerTokenAuthenticator as G}from"../transport/auth.js";import{parseAgentHarnessListenAddress as K}from"../transport/listen.js";import{createAgentHarnessNetworkListener as Q}from"../transport/network.js";import{serveStdio as X}from"../transport/stdio.js";import{parseAgentHarnessCliOptions as Z}from"./options.js";import{traceShutdown as O}from"./shutdown-diagnostics.js";export function resolveAgentHarnessProgramConfig(e,t={}){const r=Z(e),s=t.packageVersion??oe();if(r.help||r.version)return{cli:r,packageVersion:s};const a=(t.parseListenAddress??K)(r.listen);return ee(r,a),{cli:r,listen:a,packageVersion:s}}c(resolveAgentHarnessProgramConfig,"resolveAgentHarnessProgramConfig");export async function startAgentHarnessProgramApplication(e,t={},r={}){if(e.listen===void 0||e.listen.kind==="off")throw new Error("Agent Harness application cannot start without a listener");const s=V(t),a=r.processRuntime===void 0,n=r.processRuntime??await(t.createProcessRuntime??(await import("../effect-runtime/process-runtime.mjs")).createHarnessProcessRuntime)();try{const i=te({cli:e.cli,dependencies:t,listen:e.listen,packageVersion:e.packageVersion,processRuntime:n,shutdown:s,stderr:t.stderr??process.stderr});let o;return{close:c((m,p)=>(o??=re(i,m,p),o),"close"),running:i.running}}catch(i){if(!a)throw i;s.start();try{await I(n,s)}catch(o){throw new AggregateError([i,o],"Agent Harness startup and cleanup both failed")}throw i}}c(startAgentHarnessProgramApplication,"startAgentHarnessProgramApplication");export async function runAgentHarnessCli(e=process.argv.slice(2),t={}){const[{Effect:r},{makeHarnessCliMain:s}]=await Promise.all([import("effect"),import("./program.mjs")]);await r.runPromise(s(e,t))}c(runAgentHarnessCli,"runAgentHarnessCli");function ee(e,t){if((t.kind==="stdio"||t.kind==="off")&&e.wsAuth!==void 0)throw new Error(`--ws-auth cannot be used with ${t.address}`);if((t.kind==="stdio"||t.kind==="off")&&e.allowedOrigins.length>0)throw new Error(`--allowed-origin cannot be used with ${t.address}`);if(t.kind==="npipe"&&e.wsAuth===void 0)throw new Error("Windows named-pipe listeners require --ws-auth");if(t.kind!=="streamable-http"&&t.kind!=="websocket"&&e.allowInsecureRemote)throw new Error(`--allow-insecure-remote cannot be used with ${t.address}`)}c(ee,"validateHarnessListenOptions");function te({cli:e,dependencies:t,listen:r,packageVersion:s,processRuntime:a,shutdown:n,stderr:i}){const o=new AbortController,m=new Error("Agent Harness is shutting down"),p=a.run(async h=>{let d;e.wsAuth==="capability-token"?d=await(t.createTokenAuthenticator??q)({tokenFile:e.wsTokenFile,tokenSha256:e.wsTokenSha256}):e.wsAuth==="signed-bearer-token"&&(d=await(t.createSignedTokenAuthenticator??G)({audience:e.wsAudience,issuer:e.wsIssuer,maxClockSkewSeconds:e.wsMaxClockSkewSeconds,sharedSecretFile:e.wsSharedSecretFile}));const f=U(e.clientIdentity,s);await se({allowInsecureRemote:e.allowInsecureRemote,allowedOrigins:e.allowedOrigins,authenticator:d,clientIdentity:f,clientIdentityEnv:z(f),dependencies:t,gracefulShutdownSignal:o.signal,listen:r,logDir:e.logDir,packageVersion:s,processRuntime:a,processSignal:h,productConfig:e.productConfig,strictMcpConfig:e.strictMcpConfig,maxActiveSessions:e.maxActiveSessions,shutdown:n,stderr:i})});return p.catch(()=>{}),{closeReason:m,closeSignal:o,processRuntime:a,running:p,shutdown:n}}c(te,"startHarnessApplication");async function re(e,t,r){O("application","started"),e.shutdown.start(),e.closeSignal.abort(e.closeReason);let s,a=!1;try{const o=Math.max(1,e.shutdown.remainingMs());await j(e.running,o,"application shutdown")}catch(o){o!==e.closeReason&&(s=o,a=!0)}let n,i=!1;try{await I(e.processRuntime,e.shutdown,t)}catch(o){n=o,i=!0}if(!r&&a&&i)throw new AggregateError([s,n],"Agent Harness runtime and cleanup both failed");if(!r&&a)throw s;if(i)throw n;O("application","completed")}c(re,"closeHarnessApplication");async function se({allowInsecureRemote:e,allowedOrigins:t,authenticator:r,clientIdentity:s,clientIdentityEnv:a,dependencies:n,listen:i,logDir:o,packageVersion:m,processRuntime:p,processSignal:h,gracefulShutdownSignal:d,productConfig:f,strictMcpConfig:D,maxActiveSessions:x,shutdown:v,stderr:S}){const g=v,{server:C,close:k,telemetry:H,containment:E,runtimeShutdown:R,recordLifecycle:w}=await W({clientIdentity:s,clientIdentityEnv:a,dependencies:n,packageVersion:m,processRuntime:p,productConfig:f,strictMcpConfig:D,maxActiveSessions:x,shutdown:v,telemetryOptions:ne(n,o),signal:AbortSignal.any([h,d])});if(L()?.markEvent("harness-services-ready"),L()?.markStart("harness.wait-initialize","Transport setup and wait for first initialize"),i.kind==="stdio"){let l;try{l=(n.serveStdio??X)(C)}catch(u){throw await k(u).catch(()=>{}),w({component:"server",error:u,phase:"startup",process:{pid:process.pid},reason:"startup_failed",state:"startup_failed"}),u}const b=F(u=>l.close(u));w({component:"server",phase:"startup",process:{pid:process.pid},reason:"startup_completed",state:"started"}),await _(l.closed,u=>P(H,()=>B([()=>b(u),()=>k(u)],g,"stdio shutdown")),n.signalTarget,d,[E.signal,R.signal,h],{forceClose:c(u=>b(u),"forceClose"),timeouts:g}),w({component:"server",phase:"shutdown",process:{pid:process.pid},reason:"shutdown_completed",state:"stopped"});return}let A;try{A=await(n.createNetworkListener??Q)({acceptor:C,allowInsecureRemote:e,allowedOrigins:t,listen:i,authenticator:r,onWarning:c(l=>S.write(`[agent-harness] warning: ${l}
|
|
2
|
+
`),"onWarning")})}catch(l){throw await k(l).catch(()=>{}),w({component:"server",error:l,phase:"startup",process:{pid:process.pid},reason:"startup_failed",state:"startup_failed"}),l}S.write(`[agent-harness] listening on ${A.address}
|
|
3
|
+
`);const T=F(()=>A.close());w({component:"server",phase:"startup",process:{pid:process.pid},reason:"startup_completed",state:"started"}),await _(A.closed,l=>P(H,()=>J([[()=>k(l)],[()=>T()]],g,"network shutdown")),n.signalTarget,d,[E.signal,R.signal,h],{forceClose:c(()=>T(),"forceClose"),timeouts:g}),w({component:"server",phase:"shutdown",process:{pid:process.pid},reason:"shutdown_completed",state:"stopped"})}c(se,"runAgentHarnessCliRuntime");function ne(e,t){if(e.telemetry!==void 0)return e.telemetry;if(process.env.DISABLE_TELEMETRY)return{};try{const r=process.env.CODEBUDDY_CONFIG_DIR?.trim(),s=t??y.join(r?y.resolve(r):y.join(N(),".codebuddy"),"logs","harness");return{sink:(e.createTelemetryFileSink??Y)({directory:s})}}catch{return{}}}c(ne,"resolveCliTelemetry");function oe(){const e=y.resolve(import.meta.dirname,"../../package.json"),t=JSON.parse($(e,"utf8"));if(typeof t.version!="string"||t.version.length===0)throw new Error(`Agent Harness package version is missing in ${e}`);return t.version}c(oe,"readPackageVersion");
|
package/lib/cli/options.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type AgentHarnessClientIdentity } from '../runtime/client-identity.js';
|
|
2
|
-
export declare const AGENT_HARNESS_CLI_USAGE = "Usage: agent-harness [startup profiling options] [options]\n\nOptions:\n --startup-prof Write startup spans as JSON (put profiling flags first)\n --startup-prof-md Also write a Markdown startup report\n --startup-prof-dir <dir> Report directory (default: current directory)\n --startup-prof-name <name> Report file stem (default: unique timestamp and PID)\n --listen <url> stdio:// (default), http://HOST:PORT,\n ws://HOST:PORT, http+unix://PATH[:/rpc],\n ws+unix://PATH[:/rpc], unix://[ABSOLUTE_PATH], or off\n PATH is /absolute/socket or //./pipe/NAME (Windows)\n --stdio Alias for --listen stdio://\n --allowed-origin <origin> Exact browser Origin allowlist entry (repeatable)\n --allow-insecure-remote Permit authenticated non-loopback HTTP/WS without\n TLS; plaintext traffic is unsafe\n --product-config <path> Absolute versioned Host Product JSON file\n --log-dir <path> Absolute directory for structured JSONL logs\n --strict-mcp-config Only use Host-provided session mcpServers;\n ignore automatic USER and Plugin MCP sources\n --ide-name <name> Host application name reported as X-IDE-Name\n --ide-type <type> Host category reported as X-IDE-Type\n --ide-version <version> Host version reported as X-IDE-Version\n --ext-name <name> Host extension/distribution telemetry name\n --ext-version <version> Host extension version (paired with name)\n --user-agent <value> Host product token(s) appended to User-Agent\n --ws-auth <mode> capability-token or signed-bearer-token\n --ws-token-file <path> Absolute path containing the bearer token\n --ws-token-sha256 <hex> SHA-256 verifier for a bearer token\n --ws-shared-secret-file <path>\n HMAC secret for signed bearer tokens\n --ws-issuer <issuer> Required JWT issuer claim\n --ws-audience <audience> Required JWT audience claim\n --ws-max-clock-skew-seconds <seconds>\n JWT clock skew allowance (default: 30)\n -h, --help Show this help\n -V, --version Show the package version\n";
|
|
2
|
+
export declare const AGENT_HARNESS_CLI_USAGE = "Usage: agent-harness [startup profiling options] [options]\n\nOptions:\n --startup-prof Write startup spans as JSON (put profiling flags first)\n --startup-prof-md Also write a Markdown startup report\n --startup-prof-dir <dir> Report directory (default: current directory)\n --startup-prof-name <name> Report file stem (default: unique timestamp and PID)\n --listen <url> stdio:// (default), http://HOST:PORT,\n ws://HOST:PORT, http+unix://PATH[:/rpc],\n ws+unix://PATH[:/rpc], unix://[ABSOLUTE_PATH], or off\n PATH is /absolute/socket or //./pipe/NAME (Windows)\n --stdio Alias for --listen stdio://\n --allowed-origin <origin> Exact browser Origin allowlist entry (repeatable)\n --allow-insecure-remote Permit authenticated non-loopback HTTP/WS without\n TLS; plaintext traffic is unsafe\n --product-config <path> Absolute versioned Host Product JSON file\n --log-dir <path> Absolute directory for structured JSONL logs\n --max-active-sessions <count>\n Loaded session budget (default: no fixed count limit)\n --strict-mcp-config Only use Host-provided session mcpServers;\n ignore automatic USER and Plugin MCP sources\n --ide-name <name> Host application name reported as X-IDE-Name\n --ide-type <type> Host category reported as X-IDE-Type\n --ide-version <version> Host version reported as X-IDE-Version\n --ext-name <name> Host extension/distribution telemetry name\n --ext-version <version> Host extension version (paired with name)\n --user-agent <value> Host product token(s) appended to User-Agent\n --ws-auth <mode> capability-token or signed-bearer-token\n --ws-token-file <path> Absolute path containing the bearer token\n --ws-token-sha256 <hex> SHA-256 verifier for a bearer token\n --ws-shared-secret-file <path>\n HMAC secret for signed bearer tokens\n --ws-issuer <issuer> Required JWT issuer claim\n --ws-audience <audience> Required JWT audience claim\n --ws-max-clock-skew-seconds <seconds>\n JWT clock skew allowance (default: 30)\n -h, --help Show this help\n -V, --version Show the package version\n";
|
|
3
3
|
export interface AgentHarnessCliOptions {
|
|
4
4
|
allowInsecureRemote: boolean;
|
|
5
5
|
allowedOrigins: readonly string[];
|
|
@@ -9,6 +9,7 @@ export interface AgentHarnessCliOptions {
|
|
|
9
9
|
logDir?: string;
|
|
10
10
|
productConfig?: string;
|
|
11
11
|
strictMcpConfig: boolean;
|
|
12
|
+
maxActiveSessions?: number;
|
|
12
13
|
version: boolean;
|
|
13
14
|
wsAudience?: string;
|
|
14
15
|
wsAuth?: 'capability-token' | 'signed-bearer-token';
|
package/lib/cli/options.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var k=Object.defineProperty;var v=(d,e)=>k(d,"name",{value:e,configurable:!0});import*as l from"node:path";import{parseArgs as b}from"node:util";import{normalizeAgentHarnessClientIdentity as y}from"../runtime/client-identity.js";export const AGENT_HARNESS_CLI_USAGE=`Usage: agent-harness [startup profiling options] [options]
|
|
2
2
|
|
|
3
3
|
Options:
|
|
4
4
|
--startup-prof Write startup spans as JSON (put profiling flags first)
|
|
@@ -15,6 +15,8 @@ Options:
|
|
|
15
15
|
TLS; plaintext traffic is unsafe
|
|
16
16
|
--product-config <path> Absolute versioned Host Product JSON file
|
|
17
17
|
--log-dir <path> Absolute directory for structured JSONL logs
|
|
18
|
+
--max-active-sessions <count>
|
|
19
|
+
Loaded session budget (default: no fixed count limit)
|
|
18
20
|
--strict-mcp-config Only use Host-provided session mcpServers;
|
|
19
21
|
ignore automatic USER and Plugin MCP sources
|
|
20
22
|
--ide-name <name> Host application name reported as X-IDE-Name
|
|
@@ -34,4 +36,4 @@ Options:
|
|
|
34
36
|
JWT clock skew allowance (default: 30)
|
|
35
37
|
-h, --help Show this help
|
|
36
38
|
-V, --version Show the package version
|
|
37
|
-
`;export function parseAgentHarnessCliOptions(
|
|
39
|
+
`;export function parseAgentHarnessCliOptions(d){const e=b({args:[...d],allowPositionals:!1,options:{help:{short:"h",type:"boolean",default:!1},"allowed-origin":{type:"string",multiple:!0,default:[]},"allow-insecure-remote":{type:"boolean",default:!1},"ide-name":{type:"string"},"ide-type":{type:"string"},"ide-version":{type:"string"},listen:{type:"string"},"log-dir":{type:"string"},"ext-name":{type:"string"},"ext-version":{type:"string"},"product-config":{type:"string"},stdio:{type:"boolean",default:!1},"max-active-sessions":{type:"string"},"strict-mcp-config":{type:"boolean",default:!1},version:{short:"V",type:"boolean",default:!1},"ws-auth":{type:"string"},"ws-token-file":{type:"string"},"ws-token-sha256":{type:"string"},"ws-shared-secret-file":{type:"string"},"ws-issuer":{type:"string"},"ws-audience":{type:"string"},"ws-max-clock-skew-seconds":{type:"string"},"user-agent":{type:"string"}},strict:!0});if(e.values.stdio&&e.values.listen!==void 0)throw new Error("--stdio and --listen are mutually exclusive");const t=e.values["ws-auth"];if(t!==void 0&&t!=="capability-token"&&t!=="signed-bearer-token")throw new Error(`unsupported --ws-auth mode: ${t}`);const s=e.values["ws-token-file"],n=e.values["ws-token-sha256"];if(s!==void 0&&n!==void 0)throw new Error("--ws-token-file and --ws-token-sha256 are mutually exclusive");if(s!==void 0&&!l.isAbsolute(s))throw new Error("--ws-token-file must be an absolute path");if(n!==void 0&&!/^[a-fA-F0-9]{64}$/.test(n))throw new Error("--ws-token-sha256 must be a 64-character hexadecimal digest");if(t==="capability-token"&&s===void 0&&n===void 0)throw new Error("capability-token auth requires --ws-token-file or --ws-token-sha256");if(t!=="capability-token"&&(s!==void 0||n!==void 0))throw new Error("token verifier options require --ws-auth capability-token");const i=e.values["ws-shared-secret-file"],w=e.values["ws-issuer"],g=e.values["ws-audience"],c=e.values["ws-max-clock-skew-seconds"];if(i!==void 0&&!l.isAbsolute(i))throw new Error("--ws-shared-secret-file must be an absolute path");if(t==="signed-bearer-token"&&i===void 0)throw new Error("signed-bearer-token auth requires --ws-shared-secret-file");if(t!=="signed-bearer-token"&&(i!==void 0||w!==void 0||g!==void 0||c!==void 0))throw new Error("signed token options require --ws-auth signed-bearer-token");const r=c===void 0?void 0:Number(c);if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw new Error("--ws-max-clock-skew-seconds must be a non-negative integer");const h=e.values["allowed-origin"]??[];for(const a of h){let u;try{u=new URL(a)}catch{throw new Error(`--allowed-origin must be an absolute origin: ${a}`)}if(u.origin!==a||u.username||u.password)throw new Error(`--allowed-origin must not contain a path or credentials: ${a}`)}const m=e.values["max-active-sessions"],o=m===void 0?void 0:Number(m);if(o!==void 0&&(!Number.isSafeInteger(o)||o<=0))throw new Error("--max-active-sessions must be a positive integer");const p=e.values["product-config"];if(p!==void 0&&!l.isAbsolute(p))throw new Error("--product-config must be an absolute path");const f=e.values["log-dir"];if(f!==void 0&&!l.isAbsolute(f))throw new Error("--log-dir must be an absolute path");return{allowInsecureRemote:e.values["allow-insecure-remote"]??!1,allowedOrigins:h,clientIdentity:y({ideName:e.values["ide-name"],ideType:e.values["ide-type"],ideVersion:e.values["ide-version"],extName:e.values["ext-name"],extVersion:e.values["ext-version"],userAgent:e.values["user-agent"]}),help:e.values.help??!1,listen:e.values.stdio?"stdio://":e.values.listen??"stdio://",logDir:f,productConfig:p,strictMcpConfig:e.values["strict-mcp-config"]??!1,maxActiveSessions:o,version:e.values.version??!1,wsAuth:t,wsAudience:g,wsIssuer:w,wsMaxClockSkewSeconds:r,wsSharedSecretFile:i,wsTokenFile:s,wsTokenSha256:n?.toLowerCase()}}v(parseAgentHarnessCliOptions,"parseAgentHarnessCliOptions");
|
package/lib/harness/runtime.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var I=Object.defineProperty;var a=(e,o)=>I(e,"name",{value:o,configurable:!0});import{readFileSync as C}from"node:fs";import{closeHarnessProcessRuntime as x,closeWithLifecycleTelemetry as H,resolveShutdownCoordinator as R,runUntilClosed as M}from"../application/lifecycle.js";import{createApplicationServices as P}from"../application/services.js";import{createHarnessProcessRuntime as k}from"../effect-runtime/process-runtime.mjs";import{buildAgentHarnessClientIdentityEnv as L,resolveAgentHarnessClientIdentity as T}from"../runtime/client-identity.js";import{startupProfiler as N}from"../telemetry/startup-profile.js";export async function startHarness(e,o={}){if(e.signal?.throwIfAborted(),e.maxActiveSessions!==void 0&&(!Number.isSafeInteger(e.maxActiveSessions)||e.maxActiveSessions<=0))throw new RangeError("maxActiveSessions must be a positive integer");const l=e.mcp?.toolsSyncTtlMs;if(l!=null&&(!Number.isSafeInteger(l)||l<=0))throw new RangeError("mcp.toolsSyncTtlMs must be a positive integer or null");const g=o.packageVersion??JSON.parse(C(new URL("../../package.json",import.meta.url),"utf8")).version,p=T(e.host??{},g),c=R(o),m=await(o.createProcessRuntime??k)(),w=Promise.withResolvers(),t=new AbortController,d=new Error("Agent Harness is shutting down"),u=a(()=>t.abort(e.signal?.reason??d),"cancel");e.signal?.addEventListener("abort",u,{once:!0}),e.signal?.aborted&&u();const v=Promise.resolve().then(()=>m.run(async r=>{t.signal.throwIfAborted();const{server:n,close:s,telemetry:b,containment:S,runtimeShutdown:A,recordLifecycle:h}=await P({signal:AbortSignal.any([t.signal,r]),clientIdentity:p,clientIdentityEnv:L(p),dependencies:o,packageVersion:g,processRuntime:m,productConfig:e.productConfig,sandboxCenter:e.sandboxCenter,tools:{type:"preset",preset:"default",append:e.tools},hooks:e.hooks,strictMcpConfig:e.strictMcpConfig??!1,maxActiveSessions:e.maxActiveSessions,mcp:e.mcp,shutdown:c,telemetryOptions:e.telemetry??{}});if(!("connectInMemory"in n)||typeof n.connectInMemory!="function")throw await s(),new TypeError("Application Server does not implement the in-memory endpoint");N()?.markEvent("harness-services-ready"),h({component:"server",phase:"startup",process:{pid:process.pid},reason:"startup_completed",state:"started"}),w.resolve(n),await M(new Promise(()=>{}),E=>H(b,()=>s(E)),void 0,t.signal,[S.signal,A.signal,r],{timeouts:c}),h({component:"server",phase:"shutdown",process:{pid:process.pid},reason:"shutdown_completed",state:"stopped"})})),i=(async()=>{let r,n=!1;try{await v}catch(s){r=s,n=!0}t.abort(d),c.start();try{await x(m,c)}catch(s){throw n?new AggregateError([r,s],"Harness execution and cleanup failed"):s}finally{e.signal?.removeEventListener("abort",u)}if(n)throw r})();i.catch(()=>{});const f=await Promise.race([w.promise,i.then(()=>{throw new Error("Harness closed before startup completed")})]);e.signal?.aborted&&(await i,e.signal.throwIfAborted());const y=a(()=>(t.abort(d),i),"close");return{get ready(){return!t.signal.aborted&&f.ready},closed:i,connect:a((r,n)=>{if(t.signal.aborted)throw new Error("Harness is closing");return f.connect(r,n)},"connect"),connectInMemory:a(r=>{if(t.signal.aborted)throw new Error("Harness is closing");return f.connectInMemory(r)},"connectInMemory"),close:y,[Symbol.asyncDispose]:y}}a(startHarness,"startHarness");
|
package/lib/harness/types.d.ts
CHANGED
|
@@ -24,6 +24,8 @@ export interface HarnessOptions {
|
|
|
24
24
|
/** Functional hooks: register(on, options), once per Harness. Functions stay in this process. */
|
|
25
25
|
readonly hooks?: HarnessHooks;
|
|
26
26
|
readonly strictMcpConfig?: boolean;
|
|
27
|
+
/** Budget for loaded sessions, including idle ones. Omission imposes no fixed count limit. */
|
|
28
|
+
readonly maxActiveSessions?: number;
|
|
27
29
|
readonly mcp?: {
|
|
28
30
|
/** Catalog fallback refresh interval. Default: 15 minutes; null disables expiry. */
|
|
29
31
|
readonly toolsSyncTtlMs?: number | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var y=Object.defineProperty;var c=(e,t)=>y(e,"name",{value:t,configurable:!0});import*as f from"node:path";import"../checkpoint/schemas.js";import{AgentHarnessConfigWriteError as w,CONFIG_WRITE_ERROR_CODES as _}from"../config/errors.js";import{isRecord as i}from"../internal/guards.js";import{decodePluginMcpResolveResult as E}from"../protocol/plugin-mcp.js";import"../protocol/session-plugin-settings.js";import{AGENT_HARNESS_JSON_RPC_ERROR_CODES as m,AgentHarnessJsonRpcError as h}from"../server/errors.js";import"../session/turn.js";import"./codebuddy-resource-recovery.js";export const MAX_PLUGIN_MCP_SNAPSHOT_BYTES=4*1024*1024,MAX_USER_MCP_SNAPSHOT_BYTES=4*1024*1024,MAX_USER_MCP_SNAPSHOT_SERVERS=128,MAX_USER_MCP_TRANSPORT_ENTRIES=256,MAX_USER_MCP_TRANSPORT_STRING_BYTES=256*1024,SESSION_LIST_CURSOR_INVALID="SESSION_LIST_CURSOR_INVALID",CONFIG_WRITE_ERROR_CODE_SET=new Set(_),CODEBUDDY_HOST_RESOURCE_METHOD=Object.freeze({"auth/credential/read":"readManagedAuthCredential","auth/credential/refresh":"refreshManagedAuthCredential","auth/login/cancel":"cancelManagedAuthLogin","auth/login/read":"readManagedAuthLogin","auth/login/start":"startManagedAuthLogin","auth/logout":"logoutManagedAuth","auth/read":"readManagedAuth","agent/list":"listAgents","checkpoint/list":"listCheckpoints","checkpoint/read":"readCheckpoint","checkpoint/restore":"restoreCheckpoint","config/batch-write":"batchWriteConfig","config/read":"readConfig","config/value-write":"writeConfigValue","marketplace/add":"addMarketplace","marketplace/remove":"removeMarketplace","marketplace/upgrade":"upgradeMarketplace","mcp/plugin-snapshot":"resolvePluginMcp","mcp/user-snapshot":"resolveUserMcp","plugin/install":"installPlugin","plugin/list":"listPlugins","plugin/read":"readPlugin","plugin/uninstall":"uninstallPlugin","session/delete":"deleteSession","session/fork":"forkSession","session/identity":"getIdentity","session/list":"listSessions","session/replay":"replaySession","session/rewind":"rewindSession","session/terminal":"commitTerminalState","skills/config-write":"writeSkillConfig","skills/list":"listSkills"}),ALL_HOST_RESOURCES=Object.freeze(Object.keys(CODEBUDDY_HOST_RESOURCE_METHOD)),CONFIG_WRITE_RESOURCES=Object.freeze(["config/batch-write","config/value-write"]),SESSION_NOT_FOUND_RESOURCES=Object.freeze(["checkpoint/list","checkpoint/read","checkpoint/restore","session/delete","session/fork","session/replay","session/rewind","session/terminal"]),LOOKUP_RESOURCES=Object.freeze([...SESSION_NOT_FOUND_RESOURCES,"auth/login/cancel","auth/login/read","marketplace/remove","marketplace/upgrade","plugin/install","plugin/read","plugin/uninstall","skills/config-write"]),CONFIG_WRITE_ERROR_MESSAGES=Object.freeze({configLayerReadonly:"The selected configuration layer is read-only",configPathNotFound:"The configuration path was not found",configValidationError:"Configuration validation failed",configVersionConflict:"Configuration changed after it was read",userLayerNotFound:"The user configuration layer was not found"}),CONFIG_WRITE_PRIVATE_ERROR_CODES=Object.freeze({configLayerReadonly:["CONFIG_PATH_MISMATCH"],configPathNotFound:["CONFIG_PATH_NOT_FOUND"],configValidationError:["CONFIG_INVALID_EDIT","CONFIG_INVALID_FILE","CONFIG_INVALID_KEY_PATH","CONFIG_INVALID_VERSION","CONFIG_PATH_MISMATCH"],configVersionConflict:["CONFIG_VERSION_CONFLICT"],userLayerNotFound:["USER_LAYER_NOT_FOUND"]});export function requestedTurnCursor(e){if(!i(e))return;if(i(e._meta)){for(const n of["before","after"])if(typeof e._meta[n]=="string"&&e._meta[n].length>0)return e._meta[n]}const t=e.replayFrom;return i(t)&&typeof t.before=="string"&&t.before.length>0?t.before:void 0}c(requestedTurnCursor,"requestedTurnCursor");export function projectRequestedTurnCursor(e,t){const n=requestedTurnCursor(t);return n===void 0?void 0:{cursor:n}}c(projectRequestedTurnCursor,"projectRequestedTurnCursor");export function projectRequestedMessageId(e,t){return i(t)&&typeof t.messageId=="string"&&t.messageId.length>0?{messageId:t.messageId}:void 0}c(projectRequestedMessageId,"projectRequestedMessageId");export function projectRequestedAuthMethod(e,t){return i(t)&&typeof t.methodId=="string"&&t.methodId.length>0?{methodId:t.methodId}:void 0}c(projectRequestedAuthMethod,"projectRequestedAuthMethod");export const HOST_CLIENT_ERROR_RULES=Object.freeze([{code:"CONFIG_INVALID_CWD",jsonRpcCode:m.invalidParams,message:"The config/read cwd is invalid",resources:["config/read"]},{code:"CONFIG_INVALID_FILE",message:"A workspace config layer is invalid",resources:["config/read"]},{code:SESSION_LIST_CURSOR_INVALID,jsonRpcCode:m.invalidParams,message:"The session/list cursor is invalid",resources:["session/list"]},{code:"SESSION_TURN_CURSOR_NOT_FOUND",message:"The requested turn cursor was not found",projectDetails:projectRequestedTurnCursor,resources:["session/fork","session/replay","session/rewind"]},{code:"SESSION_CHECKPOINT_NOT_FOUND",message:"The requested checkpoint was not found",projectDetails:projectRequestedMessageId,publicCode:"NOT_FOUND",resources:["checkpoint/read","checkpoint/restore"]},{code:"SESSION_CHECKPOINT_UNAVAILABLE",message:"The checkpoint file state is unavailable",resources:["checkpoint/read","checkpoint/restore"]},{code:"SESSION_CHECKPOINT_TOO_LARGE",message:"The session is too large to inspect checkpoints",resources:["checkpoint/list","checkpoint/read","checkpoint/restore"]},{code:"SESSION_CWD_UNAVAILABLE",message:"The durable session workspace is unavailable",resources:["checkpoint/list","checkpoint/read","checkpoint/restore","session/rewind"]},{code:"SESSION_CHECKPOINT_RESTORE_FAILED",jsonRpcCode:m.internalError,message:"The checkpoint files could not be fully restored",resources:["checkpoint/restore"]},{code:"SESSION_FORK_TOO_LARGE",message:"The session is too large to fork",resources:["session/fork"]},{code:"SESSION_REPLAY_TOO_LARGE",message:"The session is too large to replay",resources:["session/replay"]},{code:"SESSION_REWIND_TOO_LARGE",message:"The session is too large to rewind",resources:["session/rewind"]},{code:"SESSION_TERMINAL_TOO_LARGE",message:"The session is too large to commit terminal state",resources:["session/terminal"]},{code:"SESSION_TERMINAL_CONFLICT",message:"The turn already has a different terminal state",resources:["session/terminal"]},{code:"SESSION_TERMINAL_PARENT_MISSING",message:"The durable turn has no terminal-state parent",resources:["session/terminal"]},{code:"SESSION_NOT_FOUND",message:"The session was not found",publicCode:"NOT_FOUND",resources:SESSION_NOT_FOUND_RESOURCES},{code:"SKILL_SELECTOR_AMBIGUOUS",message:"The standalone Skill selector is ambiguous",resources:["skills/config-write"]},{code:"SKILL_CONFIG_READ_ONLY",message:"The selected skills/list item is read-only",resources:["skills/config-write"]},{code:"SKILL_CONFIG_WRITE_FAILED",message:"The standalone Skill configuration could not be updated",resources:["skills/config-write"]},{code:"AUTH_REQUIRED",message:"Authentication required",resources:["auth/credential/read","auth/credential/refresh"]},{code:"AUTH_IDENTITY_CHANGED",message:"Authentication refresh changed account identity",resources:["auth/credential/refresh"]},{code:"AUTH_METHOD_NOT_AVAILABLE",message:"The requested authentication method is not available",projectDetails:projectRequestedAuthMethod,resources:["auth/login/start"]},{code:"AUTH_LOGIN_ID_CONFLICT",message:"The authentication login id is already in use",resources:["auth/login/start"]},{code:"AUTH_LOGIN_IN_PROGRESS",message:"An authentication login is already in progress",resources:["auth/login/start"]},{code:"AUTH_LOGIN_CLEANUP_IN_PROGRESS",message:"The previous authentication login is still cleaning up",resources:["auth/login/start"]},{code:"AUTH_LOGIN_NOT_FOUND",message:"The authentication login was not found",resources:["auth/login/cancel","auth/login/read"]},{code:"NOT_FOUND",message:"The requested resource was not found",resources:LOOKUP_RESOURCES},{code:"BAD_REQUEST",message:"The resource request is invalid",resources:ALL_HOST_RESOURCES}]);export function isHostClientError(e,t,n){return e>=400&&e<500||e>=500&&typeof t=="string"&&HOST_CLIENT_ERROR_RULES.some(s=>s.code===t&&s.resources.includes(n))}c(isHostClientError,"isHostClientError");export function projectHostClientError(e){if(CONFIG_WRITE_RESOURCES.includes(e.resource)&&i(e.details)){const r=e.details.config_write_error_code;if(typeof e.code=="string"&&typeof r=="string"&&CONFIG_WRITE_ERROR_CODE_SET.has(r)&&CONFIG_WRITE_PRIVATE_ERROR_CODES[r].includes(e.code))return new w(r,CONFIG_WRITE_ERROR_MESSAGES[r])}const t=typeof e.code=="string"?e.code:void 0,n=t!==void 0?HOST_CLIENT_ERROR_RULES.find(r=>r.code===t&&r.resources.includes(e.resource)):void 0;if(!n)return new h(m.invalidRequest,"Resource request rejected");const s=n.projectDetails?.(e.details,e.params);return new h(n.jsonRpcCode??m.invalidRequest,n.message,{code:n.publicCode??t,...s===void 0?{}:{details:s}})}c(projectHostClientError,"projectHostClientError");export function requiredString(e,t){if(typeof e!="string"||e.length===0)throw new Error(`CodeBuddy management response has invalid ${t}`);return e}c(requiredString,"requiredString");export function optionalString(e,t){if(!(e==null||e===""))return requiredString(e,t)}c(optionalString,"optionalString");export function nullableString(e,t){return optionalString(e,t)??null}c(nullableString,"nullableString");export function responsePlugin(e){if(!i(e)||!i(e.plugin))throw new Error("CodeBuddy management response has invalid plugin data");return e.plugin}c(responsePlugin,"responsePlugin");export function selectMarketplace(e,t){const n="marketplacePath"in t?e.marketplaces.filter(r=>r.installLocation===t.marketplacePath||r.source?.path===t.marketplacePath):(()=>{const r=t.remoteMarketplaceName,a=e.marketplaces.filter(o=>o.id===r);return a.length>0?a:e.marketplaces.filter(o=>o.displayName===r)})();if(n.length>1)throw new h(m.invalidRequest,"Plugin marketplace selector is ambiguous");const s=n[0];if(!s)throw new h(m.invalidRequest,"Plugin marketplace was not found");return s}c(selectMarketplace,"selectMarketplace");export function pluginSelector(e,t,n=e.cwd){return"marketplacePath"in e?{...n===void 0?{}:{cwd:n},marketplacePath:requiredString(t.installLocation??t.source?.path,"marketplace.installLocation"),pluginName:e.pluginName}:{...n===void 0?{}:{cwd:n},marketplaceName:t.id,pluginName:e.pluginName}}c(pluginSelector,"pluginSelector");export function projectPluginList(e,t={}){const n=parsePluginCatalog(e,t),s=n.marketplaces.map(r=>({interface:{displayName:r.displayName},name:r.id,path:r.installLocation??null,plugins:r.plugins.map(a=>projectPluginSummary(a,r))}));return{marketplaceLoadErrors:n.marketplaceLoadErrors.map(r=>({marketplacePath:n.marketplaces.find(o=>o.id===r.marketplace||o.displayName===r.marketplace)?.installLocation??r.marketplace,message:r.message})),marketplaces:s}}c(projectPluginList,"projectPluginList");export function projectConfigWriteResponse(e){if(!i(e))throw new Error("CodeBuddy management response has invalid config write data");const t=e.status;if(t!=="ok")throw new Error("CodeBuddy management response has invalid config write status");if(e.overriddenMetadata!==void 0&&e.overriddenMetadata!==null)throw new Error("CodeBuddy management response has unsupported config override metadata");return{filePath:requiredString(e.filePath,"config.filePath"),overriddenMetadata:null,status:t,version:requiredString(e.version,"config.version")}}c(projectConfigWriteResponse,"projectConfigWriteResponse");export async function readPluginWith(e,t){const n=e.cwd===void 0?{}:{cwd:e.cwd},s=parsePluginCatalog(await t.list(n),n),r=selectMarketplace(s,e),a=await t.read(pluginSelector(e,r,e.cwd===void 0?void 0:s.cwd)),o=responsePlugin(a),p=(Array.isArray(o.skills)?o.skills:o.skills===void 0?[]:[o.skills]).flatMap(l=>{const d=projectSkill(l);return d?[d]:[]});return{plugin:{agents:projectAgents(o.agents),commands:projectCommands(o.commands),description:nullableString(o.description,"plugin.description"),hooks:projectHooks(o.hooks),lspServers:projectNamedServers(o.lspServers,"plugin.lspServers"),marketplaceName:requiredString(r.id,"plugin.marketplaceName"),marketplacePath:nullableString(o.marketplacePath??r.installLocation,"plugin.marketplacePath"),mcpServers:projectMcpServers(o.mcpServers),outputStyles:projectOutputStyles(o.outputStyles),skills:p,summary:projectPluginSummary(o,r)}}}c(readPluginWith,"readPluginWith");export function parseMarketplace(e){if(!i(e))throw new Error("CodeBuddy management response has an invalid marketplace");return{description:optionalString(e.description,"marketplace.description"),displayName:requiredString(e.name,"marketplace.name"),installLocation:optionalString(e.installLocation??e.installedRoot??e.path,"marketplace.installLocation"),isBuiltIn:e.isBuiltIn===!0,id:requiredString(e.id,"marketplace.id"),source:i(e.source)?e.source:void 0,type:optionalString(e.type,"marketplace.type")}}c(parseMarketplace,"parseMarketplace");export function createPluginManagement(e){const t=c(async n=>parsePluginCatalog(await e.post("plugin/list",n),n),"readCatalog");return{async installPlugin(n){const s=await t(n.cwd===void 0?{}:{cwd:n.cwd}),r=n.cwd===void 0?void 0:s.cwd,a=selectMarketplace(s,n),o=n.scope??"user";return await e.post("plugin/install",{options:{autoEnable:!0,scope:o==="local"?"project-local":o,...n.cwd===void 0&&o==="user"?{waitForApply:!0}:{},...r===void 0?{}:{workspacePath:r}},plugin:`${n.pluginName}@${a.id}`}),{}},async uninstallPlugin(n){const s=await t(n.cwd===void 0?{}:{cwd:n.cwd}),r=n.cwd===void 0?void 0:s.cwd,a=s.marketplaces.flatMap(u=>u.plugins.map(g=>({marketplace:u,plugin:g,summary:projectPluginSummary(g,u)}))),o=n.pluginId;let p=a.filter(u=>u.summary.id===o);if(p.length===0&&(p=a.filter(u=>u.plugin.id===o||`${u.summary.name}@${u.marketplace.displayName}`===o)),p.length>1)throw new h(m.invalidRequest,`Plugin '${o}' matched more than one marketplace`);const l=p[0];if(!l)throw new h(m.invalidRequest,`Plugin '${o}' was not found`);const d=n.scope??"user";return await e.post("plugin/uninstall",{keepData:!1,options:{scope:d==="local"?"project-local":d,...n.cwd===void 0&&d==="user"?{waitForApply:!0}:{},...r===void 0?{}:{workspacePath:r}},plugin:l.summary.id}),{}},async addMarketplace(n){const s=await e.post("marketplace/add",n);if(i(s)&&typeof s.marketplaceName=="string"&&typeof s.installedRoot=="string"&&typeof s.alreadyAdded=="boolean"){const p=await t({}),l=p.marketplaces.filter(u=>u.installLocation===s.installedRoot),d=l.length===1?l[0]:marketplaceByName(p,s.marketplaceName,!0);return{alreadyAdded:s.alreadyAdded,installedRoot:s.installedRoot,marketplaceName:d.id}}const r=i(s)&&i(s.marketplace)?s.marketplace:s,a=i(r)&&typeof r.id=="string";let o=i(r)?parseMarketplace({...r,installLocation:r.installLocation??r.installedRoot,name:r.name??r.marketplaceName}):parseMarketplace(r);if(!o.installLocation){const p=await t({}),l=p.marketplaces.find(d=>d.id===o.id)??(a?void 0:marketplaceByName(p,o.displayName,!0));l&&(o=l)}return{alreadyAdded:i(s)&&(s.alreadyAdded===!0||s.alreadyExists===!0),installedRoot:requiredString(o.installLocation,"marketplace.installedRoot"),marketplaceName:o.id}},async removeMarketplace(n){const s=await t({}),r=marketplaceByName(s,n.marketplaceName,!0),a=await e.post("marketplace/remove",{marketplaceName:r.id,waitForApply:!0});return i(a)&&typeof a.marketplaceName=="string"&&(typeof a.installedRoot=="string"||a.installedRoot===null)?{installedRoot:a.installedRoot,marketplaceName:r.id}:{installedRoot:r.installLocation??null,marketplaceName:r.id}},async upgradeMarketplace(n){const s=await t({}),r=n.marketplaceName,a=r==null?s.marketplaces:[marketplaceByName(s,r,!0)],o=[],p=[];for(const l of a)try{await e.post("marketplace/upgrade",{force:!0,marketplace:l.id}),l.installLocation&&p.push(l.installLocation)}catch(d){if(e.isUnavailable(d))throw d;o.push({marketplaceName:l.id,message:"Marketplace update failed"})}return{errors:o,selectedMarketplaces:a.map(l=>l.id),upgradedRoots:p}}}}c(createPluginManagement,"createPluginManagement");export function marketplaceByName(e,t,n=!1){const s=e.marketplaces.filter(o=>o.id===t),r=s.length>0?s:n?e.marketplaces.filter(o=>o.displayName===t):[];if(r.length>1)throw new h(m.invalidRequest,`Marketplace '${t}' matched more than one catalog entry`);const a=r[0];if(!a)throw new h(m.invalidRequest,`Marketplace '${t}' was not found`);return a}c(marketplaceByName,"marketplaceByName");export function parsePluginCatalog(e,t={}){if(!i(e))throw new Error("CodeBuddy management response has invalid plugin catalog data");const n=parseArray(e.marketplaces,"marketplaces"),s=parseArray(e.marketplaceLoadErrors??[],"marketplaceLoadErrors"),r=n.map(p=>{if(!i(p))throw new Error("CodeBuddy management response has an invalid marketplace");return{...parseMarketplace(p),plugins:parseArray(p.plugins,"marketplace.plugins").map(l=>{if(!i(l))throw new Error("CodeBuddy management response has an invalid plugin");return l})}}),a=s.map(p=>{if(!i(p))throw new Error("CodeBuddy management response has an invalid marketplace error");return{marketplace:requiredString(p.marketplace??p.marketplaceName??p.marketplacePath,"marketplaceLoadErrors.marketplace"),message:requiredString(p.message,"marketplaceLoadErrors.message")}}),o=optionalString(e.cwd,"pluginCatalog.cwd");if(t.cwd!==void 0&&o===void 0)throw new Error("CodeBuddy management response is missing canonical plugin cwd");return{cwd:o,marketplaceLoadErrors:a,marketplaces:r}}c(parsePluginCatalog,"parsePluginCatalog");export function pluginSource(e,t){const n=e.source,s=optionalString(e.installedPath,"plugin.installedPath");if(i(n)&&n.source==="npm")return{package:requiredString(n.package??n.name??e.name,"plugin.source.package"),registry:nullableString(n.registry,"plugin.source.registry"),type:"npm",version:nullableString(n.version??e.version,"plugin.source.version")};if(i(n)&&(n.source==="github"||n.source==="url"||n.source==="git-subdir")){const l=n.url??(typeof n.repo=="string"?`https://github.com/${n.repo}.git`:t.source?.url??t.source?.repo);return{path:nullableString(n.path,"plugin.source.path"),refName:nullableString(n.ref??n.refName,"plugin.source.refName"),sha:nullableString(e.gitCommitSha??n.sha,"plugin.source.sha"),type:"git",url:requiredString(l,"plugin.source.url")}}const r=i(n)?optionalString(n.path,"plugin.source.path"):void 0,a=typeof n=="string"?n:r,o=a&&t.installLocation&&!f.isAbsolute(a)?f.resolve(t.installLocation,a):a;return{path:s??o??t.installLocation??t.id,type:"local"}}c(pluginSource,"pluginSource");export function parseArray(e,t){if(!Array.isArray(e))throw new Error(`CodeBuddy management response has invalid ${t} data`);return e}c(parseArray,"parseArray");export function isoTimestamp(e,t){const n=requiredString(e,t);if(!Number.isFinite(Date.parse(n)))throw new Error(`CodeBuddy host response has invalid ${t}`);return n}c(isoTimestamp,"isoTimestamp");export function parseUserMcpStringRecord(e,t){if(!i(e))throw new Error(`CodeBuddy host response has invalid ${t}`);if(Object.keys(e).length>MAX_USER_MCP_TRANSPORT_ENTRIES)throw new Error(`CodeBuddy host response has invalid ${t}`);const n={},s=new Set,r=t.includes("headers")||t.includes("env")&&process.platform==="win32";for(const a of Object.keys(e).sort()){const o=a.toLowerCase();if(a.length===0||a==="__proto__"||a==="constructor"||a==="prototype"||typeof e[a]!="string"||Buffer.byteLength(e[a])>MAX_USER_MCP_TRANSPORT_STRING_BYTES||r&&s.has(o))throw new Error(`CodeBuddy host response has invalid ${t}`);s.add(o),n[a]=e[a]}return n}c(parseUserMcpStringRecord,"parseUserMcpStringRecord");export function parseUserMcpPolicyMeta(e){if(e===void 0)return;if(!i(e))throw new Error("CodeBuddy host response has invalid USER MCP policy");const t=new Set(["alwaysLoad","builtin_tools","defer_loading","tools","transparent_proxy"]);if(Object.keys(e).some(r=>!t.has(r)))throw new Error("CodeBuddy host response has invalid USER MCP policy");for(const r of["alwaysLoad","defer_loading","transparent_proxy"])if(e[r]!==void 0&&typeof e[r]!="boolean")throw new Error("CodeBuddy host response has invalid USER MCP policy");let n;if(e.builtin_tools!==void 0){if(!Array.isArray(e.builtin_tools)||e.builtin_tools.length>MAX_USER_MCP_TRANSPORT_ENTRIES||e.builtin_tools.some(r=>typeof r!="string"||r.length===0||Buffer.byteLength(r)>MAX_USER_MCP_TRANSPORT_STRING_BYTES))throw new Error("CodeBuddy host response has invalid USER MCP policy");n=[...e.builtin_tools]}let s;if(e.tools!==void 0){if(!i(e.tools)||Object.keys(e.tools).length>MAX_USER_MCP_TRANSPORT_ENTRIES)throw new Error("CodeBuddy host response has invalid USER MCP policy");s={};for(const r of Object.keys(e.tools).sort()){const a=e.tools[r];if(r.length===0||r==="__proto__"||r==="constructor"||r==="prototype"||Buffer.byteLength(r)>MAX_USER_MCP_TRANSPORT_STRING_BYTES||!i(a)||Object.keys(a).some(o=>!["bare_name","defer_loading","server_name"].includes(o))||a.bare_name!==void 0&&typeof a.bare_name!="boolean"||a.defer_loading!==void 0&&typeof a.defer_loading!="boolean"||a.server_name!==void 0&&(typeof a.server_name!="string"||a.server_name.length===0||Buffer.byteLength(a.server_name)>MAX_USER_MCP_TRANSPORT_STRING_BYTES))throw new Error("CodeBuddy host response has invalid USER MCP policy");s[r]={...a.bare_name===void 0?{}:{bare_name:a.bare_name},...a.defer_loading===void 0?{}:{defer_loading:a.defer_loading},...a.server_name===void 0?{}:{server_name:a.server_name}}}}return{...e.alwaysLoad===void 0?{}:{alwaysLoad:e.alwaysLoad},...n===void 0?{}:{builtin_tools:n},...e.defer_loading===void 0?{}:{defer_loading:e.defer_loading},...s===void 0?{}:{tools:s},...e.transparent_proxy===void 0?{}:{transparent_proxy:e.transparent_proxy}}}c(parseUserMcpPolicyMeta,"parseUserMcpPolicyMeta");export function parseUserMcpSnapshot(e){if(!i(e)||Object.keys(e).sort().join(",")!=="errors,generation,servers,version"||e.version!==1||typeof e.generation!="string"||e.generation.length===0||Buffer.byteLength(JSON.stringify(e))>MAX_USER_MCP_SNAPSHOT_BYTES)throw new Error("CodeBuddy host response has invalid USER MCP snapshot");const t=parseArray(e.errors,"USER MCP errors");if(t.length>MAX_USER_MCP_SNAPSHOT_SERVERS)throw new Error("CodeBuddy host response has too many USER MCP errors");const n=t.map(o=>{if(!i(o)||Object.keys(o).sort().join(",")!=="code,message,serverName"||o.code!=="invalid_config"&&o.code!=="unsupported_auth"&&o.code!=="unsupported_transport")throw new Error("CodeBuddy host response has invalid USER MCP error");return{code:o.code,message:requiredString(o.message,"USER MCP error.message"),serverName:requiredString(o.serverName,"USER MCP error.serverName")}}),s=parseArray(e.servers,"USER MCP servers");if(s.length>MAX_USER_MCP_SNAPSHOT_SERVERS)throw new Error("CodeBuddy host response has too many USER MCP servers");const r=new Set,a=s.map(o=>{if(!i(o)||!["identity,logicalName,serverName,transport","_meta,identity,logicalName,serverName,transport"].includes(Object.keys(o).sort().join(","))||!i(o.transport))throw new Error("CodeBuddy host response has invalid USER MCP server");const p=requiredString(o.serverName,"USER MCP server.serverName"),l=requiredString(o.logicalName,"USER MCP server.logicalName");if(p!==l||l!==l.trim()||l.length>128||l.startsWith("_")||l.startsWith("plugin:")||r.has(l))throw new Error("CodeBuddy host response has invalid USER MCP logical name");r.add(l);const d=o.transport;if(d.type==="stdio"){if(Object.keys(d).sort().join(",")!=="args,command,cwd,env,type"||typeof d.command!="string"||!f.isAbsolute(d.command)||typeof d.cwd!="string"||!f.isAbsolute(d.cwd)||!Array.isArray(d.args)||d.args.length>MAX_USER_MCP_TRANSPORT_ENTRIES||d.args.some(u=>typeof u!="string")||d.args.some(u=>Buffer.byteLength(u)>MAX_USER_MCP_TRANSPORT_STRING_BYTES))throw new Error("CodeBuddy host response has invalid USER MCP stdio transport");return{...o._meta===void 0?{}:{_meta:parseUserMcpPolicyMeta(o._meta)},identity:requiredString(o.identity,"USER MCP server.identity"),logicalName:l,serverName:p,transport:{args:[...d.args],command:d.command,cwd:d.cwd,env:parseUserMcpStringRecord(d.env,"USER MCP stdio env"),type:"stdio"}}}if(d.type==="http"||d.type==="sse"){if(Object.keys(d).sort().join(",")!=="headers,type,url")throw new Error("CodeBuddy host response has invalid USER MCP remote transport");const u=requiredString(d.url,"USER MCP remote url");let g;try{g=new URL(u)}catch{throw new Error("CodeBuddy host response has invalid USER MCP remote url")}if(g.protocol!=="http:"&&g.protocol!=="https:")throw new Error("CodeBuddy host response has invalid USER MCP remote url");return{...o._meta===void 0?{}:{_meta:parseUserMcpPolicyMeta(o._meta)},identity:requiredString(o.identity,"USER MCP server.identity"),logicalName:l,serverName:p,transport:{headers:parseUserMcpStringRecord(d.headers,"USER MCP remote headers"),type:d.type,url:u}}}throw new Error("CodeBuddy host response has unsupported USER MCP transport")});return{errors:n,generation:e.generation,servers:a,version:1}}c(parseUserMcpSnapshot,"parseUserMcpSnapshot");export function parsePluginMcpResolveResult(e){let t;try{t=Buffer.byteLength(JSON.stringify(e))}catch{throw new Error("CodeBuddy host response has invalid Plugin MCP snapshot")}if(t>MAX_PLUGIN_MCP_SNAPSHOT_BYTES)throw new Error("CodeBuddy host response exceeds the Plugin MCP snapshot limit");const n=E(e);if(n===void 0)throw new Error("CodeBuddy host response has invalid Plugin MCP snapshot");return structuredClone(n)}c(parsePluginMcpResolveResult,"parsePluginMcpResolveResult");export const MANAGED_AUTH_LOGIN_STATES=new Set(["pending","succeeded","failed","cancelled","timed_out"]);export function parseManagedAuthSnapshot(e){if(!i(e)||typeof e.authenticated!="boolean")throw new Error("CodeBuddy management response has invalid auth snapshot data");let t=null;if(e.account!==null){if(!i(e.account))throw new Error("CodeBuddy management response has invalid auth.account data");t={id:requiredString(e.account.id,"auth.account.id"),accountType:requiredString(e.account.accountType,"auth.account.accountType"),...optionalString(e.account.avatarUrl,"auth.account.avatarUrl")?{avatarUrl:e.account.avatarUrl}:{},...optionalString(e.account.displayName,"auth.account.displayName")?{displayName:e.account.displayName}:{},...optionalString(e.account.department,"auth.account.department")?{department:e.account.department}:{},...optionalString(e.account.enterpriseId,"auth.account.enterpriseId")?{enterpriseId:e.account.enterpriseId}:{},...optionalString(e.account.enterpriseName,"auth.account.enterpriseName")?{enterpriseName:e.account.enterpriseName}:{},...optionalString(e.account.idp,"auth.account.idp")?{idp:e.account.idp}:{},...optionalString(e.account.oneidAccountId,"auth.account.oneidAccountId")?{oneidAccountId:e.account.oneidAccountId}:{}}}if(e.authenticated!==(t!==null))throw new Error("CodeBuddy management response has inconsistent auth state");return{account:t,authenticated:e.authenticated}}c(parseManagedAuthSnapshot,"parseManagedAuthSnapshot");export function parseManagedAuthCredentialProjection(e){if(!i(e)||!i(e.account)||!i(e.credential))throw new Error("CodeBuddy management response has invalid auth credential projection");const t={id:requiredString(e.account.id,"auth.credential.account.id"),accountType:requiredString(e.account.accountType,"auth.credential.account.accountType"),...optionalString(e.account.avatarUrl,"auth.credential.account.avatarUrl")?{avatarUrl:e.account.avatarUrl}:{},...optionalString(e.account.department,"auth.credential.account.department")?{department:e.account.department}:{},...optionalString(e.account.displayName,"auth.credential.account.displayName")?{displayName:e.account.displayName}:{},...optionalString(e.account.enterpriseId,"auth.credential.account.enterpriseId")?{enterpriseId:e.account.enterpriseId}:{},...optionalString(e.account.enterpriseName,"auth.credential.account.enterpriseName")?{enterpriseName:e.account.enterpriseName}:{},...optionalString(e.account.idp,"auth.credential.account.idp")?{idp:e.account.idp}:{},...optionalString(e.account.oneidAccountId,"auth.credential.account.oneidAccountId")?{oneidAccountId:e.account.oneidAccountId}:{}},n=requiredString(e.credential.accessToken,"auth.credential.accessToken"),s=optionalString(e.credential.domain,"auth.credential.domain")?e.credential.domain:void 0;if(e.credential.type==="api_key")return{account:t,credential:{accessToken:n,...s?{domain:s}:{},type:"api_key"}};if(e.credential.type!=="bearer")throw new Error("CodeBuddy management response has invalid auth credential type");return{account:t,credential:{accessToken:n,...s?{domain:s}:{},type:"bearer",...e.credential.expiresAt===void 0?{}:{expiresAt:isoTimestamp(e.credential.expiresAt,"auth.credential.expiresAt")}}}}c(parseManagedAuthCredentialProjection,"parseManagedAuthCredentialProjection");export function parseManagedAuthLogin(e){if(!i(e)||!MANAGED_AUTH_LOGIN_STATES.has(e.state))throw new Error("CodeBuddy management response has invalid auth login data");if(e.cancelled!==void 0&&typeof e.cancelled!="boolean")throw new Error("CodeBuddy management response has invalid auth login cancelled value");if(typeof e.settled!="boolean")throw new Error("CodeBuddy management response has invalid auth login settlement");return{createdAt:isoTimestamp(e.createdAt,"auth.login.createdAt"),expiresAt:isoTimestamp(e.expiresAt,"auth.login.expiresAt"),loginId:requiredString(e.loginId,"auth.login.loginId"),methodId:requiredString(e.methodId,"auth.login.methodId"),settled:e.settled,state:e.state,...optionalString(e.authUrl,"auth.login.authUrl")?{authUrl:e.authUrl}:{},...e.cancelled===void 0?{}:{cancelled:e.cancelled},...e.completedAt===void 0?{}:{completedAt:isoTimestamp(e.completedAt,"auth.login.completedAt")}}}c(parseManagedAuthLogin,"parseManagedAuthLogin");export function stringArray(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}c(stringArray,"stringArray");export function pluginInterface(e){const t=i(e.author)?e.author:void 0,n=i(e.homepage)?e.homepage.url:e.homepage;return{capabilities:stringArray(e.features),category:nullableString(e.category,"plugin.category"),description:nullableString(e.description,"plugin.description"),developerName:nullableString(t?.name,"plugin.author.name"),displayName:requiredString(e.name,"plugin.name"),websiteUrl:nullableString(n,"plugin.homepage")}}c(pluginInterface,"pluginInterface");export function projectPluginSummary(e,t){const n=requiredString(e.name,"plugin.name"),s=typeof e.installed=="boolean"?e.installed:typeof e.installedPath=="string"&&e.installedPath.length>0,r=optionalString(e.status,"plugin.status"),a=typeof e.enabled=="boolean"?e.enabled:r==="enabled",o=nullableString(e.resolvedVersion??e.version,"plugin.version");return{enabled:a,id:`${n}@${t.id}`,installed:s,interface:pluginInterface(e),keywords:stringArray(e.keywords),localVersion:s?o:null,name:n,source:pluginSource(e,t),version:o}}c(projectPluginSummary,"projectPluginSummary");export function projectSkill(e){if(typeof e=="string")return{description:"",enabled:!0,name:f.basename(e),path:e,shortDescription:null};if(!i(e))return;const t=optionalString(e.name,"plugin.skill.name");return t?{description:optionalString(e.description,"plugin.skill.description")??"",enabled:e.enabled!==!1,name:t,path:nullableString(e.path,"plugin.skill.path"),shortDescription:nullableString(e.shortDescription,"plugin.skill.shortDescription")}:void 0}c(projectSkill,"projectSkill");export const HOOK_EVENT_NAMES=new Map([["PreToolUse","preToolUse"],["PostToolUse","postToolUse"],["Notification","notification"],["UserPromptSubmit","userPromptSubmit"],["Stop","stop"],["SubagentStop","subagentStop"],["PreCompact","preCompact"],["SessionStart","sessionStart"],["SessionEnd","sessionEnd"],["WorktreeCreate","worktreeCreate"],["WorktreeRemove","worktreeRemove"],["PostToolUseFailure","postToolUseFailure"],["SubagentStart","subagentStart"],["StopFailure","stopFailure"],["PostCompact","postCompact"],["ConfigChange","configChange"],["InstructionsLoaded","instructionsLoaded"],["PermissionRequest","permissionRequest"],["PermissionDenied","permissionDenied"],["Elicitation","elicitation"],["ElicitationResult","elicitationResult"],["TaskCreated","taskCreated"],["TaskCompleted","taskCompleted"],["TeammateIdle","teammateIdle"],["Setup","setup"],["FileChanged","fileChanged"],["CwdChanged","cwdChanged"],["FinalStop","finalStop"]]),PUBLIC_HOOK_EVENT_NAMES=new Set(HOOK_EVENT_NAMES.values());export function projectHooks(e){return Array.isArray(e)?e.map((t,n)=>{if(!i(t))throw new Error(`CodeBuddy management response has invalid plugin.hooks.${n}`);const s=requiredString(t.eventName,`plugin.hooks.${n}.eventName`),r=HOOK_EVENT_NAMES.get(s)??(PUBLIC_HOOK_EVENT_NAMES.has(s)?s:void 0);if(!r)throw new Error(`CodeBuddy management response has invalid plugin.hooks.${n}.eventName`);return{eventName:r,key:requiredString(t.key,`plugin.hooks.${n}.key`)}}):i(e)?Object.keys(e).flatMap(t=>{const n=HOOK_EVENT_NAMES.get(t)??(PUBLIC_HOOK_EVENT_NAMES.has(t)?t:void 0);return n?[{eventName:n,key:t}]:[]}):[]}c(projectHooks,"projectHooks");export function projectMcpServers(e){if(e==null||typeof e=="string")return[];if(Array.isArray(e))return[...new Set(e.map((t,n)=>requiredString(t,`plugin.mcpServers.${n}`)))];if(!i(e))throw new Error("CodeBuddy management response has invalid plugin.mcpServers");return Object.keys(e).map((t,n)=>requiredString(t,`plugin.mcpServers.${n}`))}c(projectMcpServers,"projectMcpServers");export function componentItems(e,t){if(e==null)return[];if(Array.isArray(e))return e;if(typeof e=="string")return[];if(i(e))return[e];throw new Error(`CodeBuddy management response has invalid ${t}`)}c(componentItems,"componentItems");export function projectCommands(e){return componentItems(e,"plugin.commands").flatMap((t,n)=>{if(typeof t=="string")return[];if(!i(t))throw new Error(`CodeBuddy management response has invalid plugin.commands.${n}`);return[{argumentHint:nullableString(t.argumentHint??t["argument-hint"],`plugin.commands.${n}.argumentHint`),description:nullableString(t.description,`plugin.commands.${n}.description`),name:requiredString(t.name,`plugin.commands.${n}.name`)}]})}c(projectCommands,"projectCommands");export function projectAgents(e){return componentItems(e,"plugin.agents").flatMap((t,n)=>{if(typeof t=="string")return[];if(!i(t))throw new Error(`CodeBuddy management response has invalid plugin.agents.${n}`);return[{description:nullableString(t.description,`plugin.agents.${n}.description`),name:requiredString(t.name,`plugin.agents.${n}.name`)}]})}c(projectAgents,"projectAgents");export function projectNamedServers(e,t){if(e==null)return[];if(typeof e=="string")return[];if(Array.isArray(e))return[...new Set(e.map((n,s)=>{if(typeof n=="string")return requiredString(n,`${t}.${s}`);if(i(n))return requiredString(n.name,`${t}.${s}.name`);throw new Error(`CodeBuddy management response has invalid ${t}.${s}`)}))];if(!i(e))throw new Error(`CodeBuddy management response has invalid ${t}`);return Object.keys(e).map((n,s)=>requiredString(n,`${t}.${s}`))}c(projectNamedServers,"projectNamedServers");export function projectOutputStyles(e){return componentItems(e,"plugin.outputStyles").flatMap((t,n)=>{if(typeof t=="string")return[];if(!i(t))throw new Error(`CodeBuddy management response has invalid plugin.outputStyles.${n}`);return[{description:nullableString(t.description,`plugin.outputStyles.${n}.description`),name:requiredString(t.name,`plugin.outputStyles.${n}.name`)}]})}c(projectOutputStyles,"projectOutputStyles");
|
|
1
|
+
var y=Object.defineProperty;var c=(e,t)=>y(e,"name",{value:t,configurable:!0});import*as f from"node:path";import"../checkpoint/schemas.js";import{AgentHarnessConfigWriteError as _,CONFIG_WRITE_ERROR_CODES as w}from"../config/errors.js";import{isRecord as i}from"../internal/guards.js";import{decodePluginMcpResolveResult as S}from"../protocol/plugin-mcp.js";import"../protocol/session-plugin-settings.js";import{AGENT_HARNESS_JSON_RPC_ERROR_CODES as m,AgentHarnessJsonRpcError as h}from"../server/errors.js";import"../session/turn.js";import"./codebuddy-resource-recovery.js";export const MAX_PLUGIN_MCP_SNAPSHOT_BYTES=4*1024*1024,MAX_USER_MCP_SNAPSHOT_BYTES=4*1024*1024,MAX_USER_MCP_SNAPSHOT_SERVERS=128,MAX_USER_MCP_TRANSPORT_ENTRIES=256,MAX_USER_MCP_TRANSPORT_STRING_BYTES=256*1024,SESSION_LIST_CURSOR_INVALID="SESSION_LIST_CURSOR_INVALID",CONFIG_WRITE_ERROR_CODE_SET=new Set(w),CODEBUDDY_HOST_RESOURCE_METHOD=Object.freeze({"auth/credential/read":"readManagedAuthCredential","auth/credential/refresh":"refreshManagedAuthCredential","auth/login/cancel":"cancelManagedAuthLogin","auth/login/read":"readManagedAuthLogin","auth/login/start":"startManagedAuthLogin","auth/logout":"logoutManagedAuth","auth/read":"readManagedAuth","agent/list":"listAgents","checkpoint/list":"listCheckpoints","checkpoint/read":"readCheckpoint","checkpoint/restore":"restoreCheckpoint","config/batch-write":"batchWriteConfig","config/read":"readConfig","config/value-write":"writeConfigValue","marketplace/add":"addMarketplace","marketplace/remove":"removeMarketplace","marketplace/upgrade":"upgradeMarketplace","mcp/plugin-snapshot":"resolvePluginMcp","mcp/user-snapshot":"resolveUserMcp","plugin/install":"installPlugin","plugin/list":"listPlugins","plugin/read":"readPlugin","plugin/uninstall":"uninstallPlugin","session/delete":"deleteSession","session/fork":"forkSession","session/identity":"getIdentity","session/list":"listSessions","session/replay":"replaySession","session/rewind":"rewindSession","session/terminal":"commitTerminalState","skills/config-write":"writeSkillConfig","skills/list":"listSkills"}),ALL_HOST_RESOURCES=Object.freeze(Object.keys(CODEBUDDY_HOST_RESOURCE_METHOD)),CONFIG_WRITE_RESOURCES=Object.freeze(["config/batch-write","config/value-write"]),SESSION_NOT_FOUND_RESOURCES=Object.freeze(["checkpoint/list","checkpoint/read","checkpoint/restore","session/delete","session/fork","session/replay","session/rewind","session/terminal"]),LOOKUP_RESOURCES=Object.freeze([...SESSION_NOT_FOUND_RESOURCES,"auth/login/cancel","auth/login/read","marketplace/remove","marketplace/upgrade","plugin/install","plugin/read","plugin/uninstall","skills/config-write"]),CONFIG_WRITE_ERROR_MESSAGES=Object.freeze({configLayerReadonly:"The selected configuration layer is read-only",configPathNotFound:"The configuration path was not found",configValidationError:"Configuration validation failed",configVersionConflict:"Configuration changed after it was read",userLayerNotFound:"The user configuration layer was not found"}),CONFIG_WRITE_PRIVATE_ERROR_CODES=Object.freeze({configLayerReadonly:["CONFIG_PATH_MISMATCH"],configPathNotFound:["CONFIG_PATH_NOT_FOUND"],configValidationError:["CONFIG_INVALID_EDIT","CONFIG_INVALID_FILE","CONFIG_INVALID_KEY_PATH","CONFIG_INVALID_VERSION","CONFIG_PATH_MISMATCH"],configVersionConflict:["CONFIG_VERSION_CONFLICT"],userLayerNotFound:["USER_LAYER_NOT_FOUND"]});export function requestedTurnCursor(e){if(!i(e))return;if(i(e._meta)){for(const n of["before","after"])if(typeof e._meta[n]=="string"&&e._meta[n].length>0)return e._meta[n]}const t=e.replayFrom;return i(t)&&typeof t.before=="string"&&t.before.length>0?t.before:void 0}c(requestedTurnCursor,"requestedTurnCursor");export function projectRequestedTurnCursor(e,t){const n=requestedTurnCursor(t);return n===void 0?void 0:{cursor:n}}c(projectRequestedTurnCursor,"projectRequestedTurnCursor");export function projectRequestedMessageId(e,t){return i(t)&&typeof t.messageId=="string"&&t.messageId.length>0?{messageId:t.messageId}:void 0}c(projectRequestedMessageId,"projectRequestedMessageId");export function projectRequestedAuthMethod(e,t){return i(t)&&typeof t.methodId=="string"&&t.methodId.length>0?{methodId:t.methodId}:void 0}c(projectRequestedAuthMethod,"projectRequestedAuthMethod");export const HOST_CLIENT_ERROR_RULES=Object.freeze([{code:"CONFIG_INVALID_CWD",jsonRpcCode:m.invalidParams,message:"The config/read cwd is invalid",resources:["config/read"]},{code:"CONFIG_INVALID_FILE",message:"A workspace config layer is invalid",resources:["config/read"]},{code:SESSION_LIST_CURSOR_INVALID,jsonRpcCode:m.invalidParams,message:"The session/list cursor is invalid",resources:["session/list"]},{code:"SESSION_TURN_CURSOR_NOT_FOUND",message:"The requested turn cursor was not found",projectDetails:projectRequestedTurnCursor,resources:["session/fork","session/replay","session/rewind"]},{code:"SESSION_CHECKPOINT_NOT_FOUND",message:"The requested checkpoint was not found",projectDetails:projectRequestedMessageId,publicCode:"NOT_FOUND",resources:["checkpoint/read","checkpoint/restore"]},{code:"SESSION_CHECKPOINT_UNAVAILABLE",message:"The checkpoint file state is unavailable",resources:["checkpoint/read","checkpoint/restore"]},{code:"SESSION_CHECKPOINT_TOO_LARGE",message:"The session is too large to inspect checkpoints",resources:["checkpoint/list","checkpoint/read","checkpoint/restore"]},{code:"SESSION_CWD_UNAVAILABLE",message:"The durable session workspace is unavailable",resources:["checkpoint/list","checkpoint/read","checkpoint/restore","session/rewind"]},{code:"SESSION_CHECKPOINT_RESTORE_FAILED",jsonRpcCode:m.internalError,message:"The checkpoint files could not be fully restored",resources:["checkpoint/restore"]},{code:"SESSION_HISTORY_INVALID",message:"The persisted session history is inconsistent or incomplete",resources:["session/fork","session/delete"]},{code:"SESSION_FORK_TOO_LARGE",message:"The session is too large to fork",resources:["session/fork"]},{code:"SESSION_REPLAY_TOO_LARGE",message:"The session is too large to replay",resources:["session/replay"]},{code:"SESSION_REWIND_TOO_LARGE",message:"The session is too large to rewind",resources:["session/rewind"]},{code:"SESSION_TERMINAL_TOO_LARGE",message:"The session is too large to commit terminal state",resources:["session/terminal"]},{code:"SESSION_TERMINAL_CONFLICT",message:"The turn already has a different terminal state",resources:["session/terminal"]},{code:"SESSION_TERMINAL_PARENT_MISSING",message:"The durable turn has no terminal-state parent",resources:["session/terminal"]},{code:"SESSION_NOT_FOUND",message:"The session was not found",publicCode:"NOT_FOUND",resources:SESSION_NOT_FOUND_RESOURCES},{code:"SKILL_SELECTOR_AMBIGUOUS",message:"The standalone Skill selector is ambiguous",resources:["skills/config-write"]},{code:"SKILL_CONFIG_READ_ONLY",message:"The selected skills/list item is read-only",resources:["skills/config-write"]},{code:"SKILL_CONFIG_WRITE_FAILED",message:"The standalone Skill configuration could not be updated",resources:["skills/config-write"]},{code:"AUTH_REQUIRED",message:"Authentication required",resources:["auth/credential/read","auth/credential/refresh"]},{code:"AUTH_IDENTITY_CHANGED",message:"Authentication refresh changed account identity",resources:["auth/credential/refresh"]},{code:"AUTH_METHOD_NOT_AVAILABLE",message:"The requested authentication method is not available",projectDetails:projectRequestedAuthMethod,resources:["auth/login/start"]},{code:"AUTH_LOGIN_ID_CONFLICT",message:"The authentication login id is already in use",resources:["auth/login/start"]},{code:"AUTH_LOGIN_IN_PROGRESS",message:"An authentication login is already in progress",resources:["auth/login/start"]},{code:"AUTH_LOGIN_CLEANUP_IN_PROGRESS",message:"The previous authentication login is still cleaning up",resources:["auth/login/start"]},{code:"AUTH_LOGIN_NOT_FOUND",message:"The authentication login was not found",resources:["auth/login/cancel","auth/login/read"]},{code:"NOT_FOUND",message:"The requested resource was not found",resources:LOOKUP_RESOURCES},{code:"BAD_REQUEST",message:"The resource request is invalid",resources:ALL_HOST_RESOURCES}]);export function isHostClientError(e,t,n){return e>=400&&e<500||e>=500&&typeof t=="string"&&HOST_CLIENT_ERROR_RULES.some(s=>s.code===t&&s.resources.includes(n))}c(isHostClientError,"isHostClientError");export function projectHostClientError(e){if(CONFIG_WRITE_RESOURCES.includes(e.resource)&&i(e.details)){const r=e.details.config_write_error_code;if(typeof e.code=="string"&&typeof r=="string"&&CONFIG_WRITE_ERROR_CODE_SET.has(r)&&CONFIG_WRITE_PRIVATE_ERROR_CODES[r].includes(e.code))return new _(r,CONFIG_WRITE_ERROR_MESSAGES[r])}const t=typeof e.code=="string"?e.code:void 0,n=t!==void 0?HOST_CLIENT_ERROR_RULES.find(r=>r.code===t&&r.resources.includes(e.resource)):void 0;if(!n)return new h(m.invalidRequest,"Resource request rejected");const s=n.projectDetails?.(e.details,e.params);return new h(n.jsonRpcCode??m.invalidRequest,n.message,{code:n.publicCode??t,...s===void 0?{}:{details:s}})}c(projectHostClientError,"projectHostClientError");export function requiredString(e,t){if(typeof e!="string"||e.length===0)throw new Error(`CodeBuddy management response has invalid ${t}`);return e}c(requiredString,"requiredString");export function optionalString(e,t){if(!(e==null||e===""))return requiredString(e,t)}c(optionalString,"optionalString");export function nullableString(e,t){return optionalString(e,t)??null}c(nullableString,"nullableString");export function responsePlugin(e){if(!i(e)||!i(e.plugin))throw new Error("CodeBuddy management response has invalid plugin data");return e.plugin}c(responsePlugin,"responsePlugin");export function selectMarketplace(e,t){const n="marketplacePath"in t?e.marketplaces.filter(r=>r.installLocation===t.marketplacePath||r.source?.path===t.marketplacePath):(()=>{const r=t.remoteMarketplaceName,a=e.marketplaces.filter(o=>o.id===r);return a.length>0?a:e.marketplaces.filter(o=>o.displayName===r)})();if(n.length>1)throw new h(m.invalidRequest,"Plugin marketplace selector is ambiguous");const s=n[0];if(!s)throw new h(m.invalidRequest,"Plugin marketplace was not found");return s}c(selectMarketplace,"selectMarketplace");export function pluginSelector(e,t,n=e.cwd){return"marketplacePath"in e?{...n===void 0?{}:{cwd:n},marketplacePath:requiredString(t.installLocation??t.source?.path,"marketplace.installLocation"),pluginName:e.pluginName}:{...n===void 0?{}:{cwd:n},marketplaceName:t.id,pluginName:e.pluginName}}c(pluginSelector,"pluginSelector");export function projectPluginList(e,t={}){const n=parsePluginCatalog(e,t),s=n.marketplaces.map(r=>({interface:{displayName:r.displayName},name:r.id,path:r.installLocation??null,plugins:r.plugins.map(a=>projectPluginSummary(a,r))}));return{marketplaceLoadErrors:n.marketplaceLoadErrors.map(r=>({marketplacePath:n.marketplaces.find(o=>o.id===r.marketplace||o.displayName===r.marketplace)?.installLocation??r.marketplace,message:r.message})),marketplaces:s}}c(projectPluginList,"projectPluginList");export function projectConfigWriteResponse(e){if(!i(e))throw new Error("CodeBuddy management response has invalid config write data");const t=e.status;if(t!=="ok")throw new Error("CodeBuddy management response has invalid config write status");if(e.overriddenMetadata!==void 0&&e.overriddenMetadata!==null)throw new Error("CodeBuddy management response has unsupported config override metadata");return{filePath:requiredString(e.filePath,"config.filePath"),overriddenMetadata:null,status:t,version:requiredString(e.version,"config.version")}}c(projectConfigWriteResponse,"projectConfigWriteResponse");export async function readPluginWith(e,t){const n=e.cwd===void 0?{}:{cwd:e.cwd},s=parsePluginCatalog(await t.list(n),n),r=selectMarketplace(s,e),a=await t.read(pluginSelector(e,r,e.cwd===void 0?void 0:s.cwd)),o=responsePlugin(a),p=(Array.isArray(o.skills)?o.skills:o.skills===void 0?[]:[o.skills]).flatMap(l=>{const d=projectSkill(l);return d?[d]:[]});return{plugin:{agents:projectAgents(o.agents),commands:projectCommands(o.commands),description:nullableString(o.description,"plugin.description"),hooks:projectHooks(o.hooks),lspServers:projectNamedServers(o.lspServers,"plugin.lspServers"),marketplaceName:requiredString(r.id,"plugin.marketplaceName"),marketplacePath:nullableString(o.marketplacePath??r.installLocation,"plugin.marketplacePath"),mcpServers:projectMcpServers(o.mcpServers),outputStyles:projectOutputStyles(o.outputStyles),skills:p,summary:projectPluginSummary(o,r)}}}c(readPluginWith,"readPluginWith");export function parseMarketplace(e){if(!i(e))throw new Error("CodeBuddy management response has an invalid marketplace");return{description:optionalString(e.description,"marketplace.description"),displayName:requiredString(e.name,"marketplace.name"),installLocation:optionalString(e.installLocation??e.installedRoot??e.path,"marketplace.installLocation"),isBuiltIn:e.isBuiltIn===!0,id:requiredString(e.id,"marketplace.id"),source:i(e.source)?e.source:void 0,type:optionalString(e.type,"marketplace.type")}}c(parseMarketplace,"parseMarketplace");export function createPluginManagement(e){const t=c(async n=>parsePluginCatalog(await e.post("plugin/list",n),n),"readCatalog");return{async installPlugin(n){const s=await t(n.cwd===void 0?{}:{cwd:n.cwd}),r=n.cwd===void 0?void 0:s.cwd,a=selectMarketplace(s,n),o=n.scope??"user";return await e.post("plugin/install",{options:{autoEnable:!0,scope:o==="local"?"project-local":o,...n.cwd===void 0&&o==="user"?{waitForApply:!0}:{},...r===void 0?{}:{workspacePath:r}},plugin:`${n.pluginName}@${a.id}`}),{}},async uninstallPlugin(n){const s=await t(n.cwd===void 0?{}:{cwd:n.cwd}),r=n.cwd===void 0?void 0:s.cwd,a=s.marketplaces.flatMap(u=>u.plugins.map(g=>({marketplace:u,plugin:g,summary:projectPluginSummary(g,u)}))),o=n.pluginId;let p=a.filter(u=>u.summary.id===o);if(p.length===0&&(p=a.filter(u=>u.plugin.id===o||`${u.summary.name}@${u.marketplace.displayName}`===o)),p.length>1)throw new h(m.invalidRequest,`Plugin '${o}' matched more than one marketplace`);const l=p[0];if(!l)throw new h(m.invalidRequest,`Plugin '${o}' was not found`);const d=n.scope??"user";return await e.post("plugin/uninstall",{keepData:!1,options:{scope:d==="local"?"project-local":d,...n.cwd===void 0&&d==="user"?{waitForApply:!0}:{},...r===void 0?{}:{workspacePath:r}},plugin:l.summary.id}),{}},async addMarketplace(n){const s=await e.post("marketplace/add",n);if(i(s)&&typeof s.marketplaceName=="string"&&typeof s.installedRoot=="string"&&typeof s.alreadyAdded=="boolean"){const p=await t({}),l=p.marketplaces.filter(u=>u.installLocation===s.installedRoot),d=l.length===1?l[0]:marketplaceByName(p,s.marketplaceName,!0);return{alreadyAdded:s.alreadyAdded,installedRoot:s.installedRoot,marketplaceName:d.id}}const r=i(s)&&i(s.marketplace)?s.marketplace:s,a=i(r)&&typeof r.id=="string";let o=i(r)?parseMarketplace({...r,installLocation:r.installLocation??r.installedRoot,name:r.name??r.marketplaceName}):parseMarketplace(r);if(!o.installLocation){const p=await t({}),l=p.marketplaces.find(d=>d.id===o.id)??(a?void 0:marketplaceByName(p,o.displayName,!0));l&&(o=l)}return{alreadyAdded:i(s)&&(s.alreadyAdded===!0||s.alreadyExists===!0),installedRoot:requiredString(o.installLocation,"marketplace.installedRoot"),marketplaceName:o.id}},async removeMarketplace(n){const s=await t({}),r=marketplaceByName(s,n.marketplaceName,!0),a=await e.post("marketplace/remove",{marketplaceName:r.id,waitForApply:!0});return i(a)&&typeof a.marketplaceName=="string"&&(typeof a.installedRoot=="string"||a.installedRoot===null)?{installedRoot:a.installedRoot,marketplaceName:r.id}:{installedRoot:r.installLocation??null,marketplaceName:r.id}},async upgradeMarketplace(n){const s=await t({}),r=n.marketplaceName,a=r==null?s.marketplaces:[marketplaceByName(s,r,!0)],o=[],p=[];for(const l of a)try{await e.post("marketplace/upgrade",{force:!0,marketplace:l.id}),l.installLocation&&p.push(l.installLocation)}catch(d){if(e.isUnavailable(d))throw d;o.push({marketplaceName:l.id,message:"Marketplace update failed"})}return{errors:o,selectedMarketplaces:a.map(l=>l.id),upgradedRoots:p}}}}c(createPluginManagement,"createPluginManagement");export function marketplaceByName(e,t,n=!1){const s=e.marketplaces.filter(o=>o.id===t),r=s.length>0?s:n?e.marketplaces.filter(o=>o.displayName===t):[];if(r.length>1)throw new h(m.invalidRequest,`Marketplace '${t}' matched more than one catalog entry`);const a=r[0];if(!a)throw new h(m.invalidRequest,`Marketplace '${t}' was not found`);return a}c(marketplaceByName,"marketplaceByName");export function parsePluginCatalog(e,t={}){if(!i(e))throw new Error("CodeBuddy management response has invalid plugin catalog data");const n=parseArray(e.marketplaces,"marketplaces"),s=parseArray(e.marketplaceLoadErrors??[],"marketplaceLoadErrors"),r=n.map(p=>{if(!i(p))throw new Error("CodeBuddy management response has an invalid marketplace");return{...parseMarketplace(p),plugins:parseArray(p.plugins,"marketplace.plugins").map(l=>{if(!i(l))throw new Error("CodeBuddy management response has an invalid plugin");return l})}}),a=s.map(p=>{if(!i(p))throw new Error("CodeBuddy management response has an invalid marketplace error");return{marketplace:requiredString(p.marketplace??p.marketplaceName??p.marketplacePath,"marketplaceLoadErrors.marketplace"),message:requiredString(p.message,"marketplaceLoadErrors.message")}}),o=optionalString(e.cwd,"pluginCatalog.cwd");if(t.cwd!==void 0&&o===void 0)throw new Error("CodeBuddy management response is missing canonical plugin cwd");return{cwd:o,marketplaceLoadErrors:a,marketplaces:r}}c(parsePluginCatalog,"parsePluginCatalog");export function pluginSource(e,t){const n=e.source,s=optionalString(e.installedPath,"plugin.installedPath");if(i(n)&&n.source==="npm")return{package:requiredString(n.package??n.name??e.name,"plugin.source.package"),registry:nullableString(n.registry,"plugin.source.registry"),type:"npm",version:nullableString(n.version??e.version,"plugin.source.version")};if(i(n)&&(n.source==="github"||n.source==="url"||n.source==="git-subdir")){const l=n.url??(typeof n.repo=="string"?`https://github.com/${n.repo}.git`:t.source?.url??t.source?.repo);return{path:nullableString(n.path,"plugin.source.path"),refName:nullableString(n.ref??n.refName,"plugin.source.refName"),sha:nullableString(e.gitCommitSha??n.sha,"plugin.source.sha"),type:"git",url:requiredString(l,"plugin.source.url")}}const r=i(n)?optionalString(n.path,"plugin.source.path"):void 0,a=typeof n=="string"?n:r,o=a&&t.installLocation&&!f.isAbsolute(a)?f.resolve(t.installLocation,a):a;return{path:s??o??t.installLocation??t.id,type:"local"}}c(pluginSource,"pluginSource");export function parseArray(e,t){if(!Array.isArray(e))throw new Error(`CodeBuddy management response has invalid ${t} data`);return e}c(parseArray,"parseArray");export function isoTimestamp(e,t){const n=requiredString(e,t);if(!Number.isFinite(Date.parse(n)))throw new Error(`CodeBuddy host response has invalid ${t}`);return n}c(isoTimestamp,"isoTimestamp");export function parseUserMcpStringRecord(e,t){if(!i(e))throw new Error(`CodeBuddy host response has invalid ${t}`);if(Object.keys(e).length>MAX_USER_MCP_TRANSPORT_ENTRIES)throw new Error(`CodeBuddy host response has invalid ${t}`);const n={},s=new Set,r=t.includes("headers")||t.includes("env")&&process.platform==="win32";for(const a of Object.keys(e).sort()){const o=a.toLowerCase();if(a.length===0||a==="__proto__"||a==="constructor"||a==="prototype"||typeof e[a]!="string"||Buffer.byteLength(e[a])>MAX_USER_MCP_TRANSPORT_STRING_BYTES||r&&s.has(o))throw new Error(`CodeBuddy host response has invalid ${t}`);s.add(o),n[a]=e[a]}return n}c(parseUserMcpStringRecord,"parseUserMcpStringRecord");export function parseUserMcpPolicyMeta(e){if(e===void 0)return;if(!i(e))throw new Error("CodeBuddy host response has invalid USER MCP policy");const t=new Set(["alwaysLoad","builtin_tools","defer_loading","tools","transparent_proxy"]);if(Object.keys(e).some(r=>!t.has(r)))throw new Error("CodeBuddy host response has invalid USER MCP policy");for(const r of["alwaysLoad","defer_loading","transparent_proxy"])if(e[r]!==void 0&&typeof e[r]!="boolean")throw new Error("CodeBuddy host response has invalid USER MCP policy");let n;if(e.builtin_tools!==void 0){if(!Array.isArray(e.builtin_tools)||e.builtin_tools.length>MAX_USER_MCP_TRANSPORT_ENTRIES||e.builtin_tools.some(r=>typeof r!="string"||r.length===0||Buffer.byteLength(r)>MAX_USER_MCP_TRANSPORT_STRING_BYTES))throw new Error("CodeBuddy host response has invalid USER MCP policy");n=[...e.builtin_tools]}let s;if(e.tools!==void 0){if(!i(e.tools)||Object.keys(e.tools).length>MAX_USER_MCP_TRANSPORT_ENTRIES)throw new Error("CodeBuddy host response has invalid USER MCP policy");s={};for(const r of Object.keys(e.tools).sort()){const a=e.tools[r];if(r.length===0||r==="__proto__"||r==="constructor"||r==="prototype"||Buffer.byteLength(r)>MAX_USER_MCP_TRANSPORT_STRING_BYTES||!i(a)||Object.keys(a).some(o=>!["bare_name","defer_loading","server_name"].includes(o))||a.bare_name!==void 0&&typeof a.bare_name!="boolean"||a.defer_loading!==void 0&&typeof a.defer_loading!="boolean"||a.server_name!==void 0&&(typeof a.server_name!="string"||a.server_name.length===0||Buffer.byteLength(a.server_name)>MAX_USER_MCP_TRANSPORT_STRING_BYTES))throw new Error("CodeBuddy host response has invalid USER MCP policy");s[r]={...a.bare_name===void 0?{}:{bare_name:a.bare_name},...a.defer_loading===void 0?{}:{defer_loading:a.defer_loading},...a.server_name===void 0?{}:{server_name:a.server_name}}}}return{...e.alwaysLoad===void 0?{}:{alwaysLoad:e.alwaysLoad},...n===void 0?{}:{builtin_tools:n},...e.defer_loading===void 0?{}:{defer_loading:e.defer_loading},...s===void 0?{}:{tools:s},...e.transparent_proxy===void 0?{}:{transparent_proxy:e.transparent_proxy}}}c(parseUserMcpPolicyMeta,"parseUserMcpPolicyMeta");export function parseUserMcpSnapshot(e){if(!i(e)||Object.keys(e).sort().join(",")!=="errors,generation,servers,version"||e.version!==1||typeof e.generation!="string"||e.generation.length===0||Buffer.byteLength(JSON.stringify(e))>MAX_USER_MCP_SNAPSHOT_BYTES)throw new Error("CodeBuddy host response has invalid USER MCP snapshot");const t=parseArray(e.errors,"USER MCP errors");if(t.length>MAX_USER_MCP_SNAPSHOT_SERVERS)throw new Error("CodeBuddy host response has too many USER MCP errors");const n=t.map(o=>{if(!i(o)||Object.keys(o).sort().join(",")!=="code,message,serverName"||o.code!=="invalid_config"&&o.code!=="unsupported_auth"&&o.code!=="unsupported_transport")throw new Error("CodeBuddy host response has invalid USER MCP error");return{code:o.code,message:requiredString(o.message,"USER MCP error.message"),serverName:requiredString(o.serverName,"USER MCP error.serverName")}}),s=parseArray(e.servers,"USER MCP servers");if(s.length>MAX_USER_MCP_SNAPSHOT_SERVERS)throw new Error("CodeBuddy host response has too many USER MCP servers");const r=new Set,a=s.map(o=>{if(!i(o)||!["identity,logicalName,serverName,transport","_meta,identity,logicalName,serverName,transport"].includes(Object.keys(o).sort().join(","))||!i(o.transport))throw new Error("CodeBuddy host response has invalid USER MCP server");const p=requiredString(o.serverName,"USER MCP server.serverName"),l=requiredString(o.logicalName,"USER MCP server.logicalName");if(p!==l||l!==l.trim()||l.length>128||l.startsWith("_")||l.startsWith("plugin:")||r.has(l))throw new Error("CodeBuddy host response has invalid USER MCP logical name");r.add(l);const d=o.transport;if(d.type==="stdio"){if(Object.keys(d).sort().join(",")!=="args,command,cwd,env,type"||typeof d.command!="string"||!f.isAbsolute(d.command)||typeof d.cwd!="string"||!f.isAbsolute(d.cwd)||!Array.isArray(d.args)||d.args.length>MAX_USER_MCP_TRANSPORT_ENTRIES||d.args.some(u=>typeof u!="string")||d.args.some(u=>Buffer.byteLength(u)>MAX_USER_MCP_TRANSPORT_STRING_BYTES))throw new Error("CodeBuddy host response has invalid USER MCP stdio transport");return{...o._meta===void 0?{}:{_meta:parseUserMcpPolicyMeta(o._meta)},identity:requiredString(o.identity,"USER MCP server.identity"),logicalName:l,serverName:p,transport:{args:[...d.args],command:d.command,cwd:d.cwd,env:parseUserMcpStringRecord(d.env,"USER MCP stdio env"),type:"stdio"}}}if(d.type==="http"||d.type==="sse"){if(Object.keys(d).sort().join(",")!=="headers,type,url")throw new Error("CodeBuddy host response has invalid USER MCP remote transport");const u=requiredString(d.url,"USER MCP remote url");let g;try{g=new URL(u)}catch{throw new Error("CodeBuddy host response has invalid USER MCP remote url")}if(g.protocol!=="http:"&&g.protocol!=="https:")throw new Error("CodeBuddy host response has invalid USER MCP remote url");return{...o._meta===void 0?{}:{_meta:parseUserMcpPolicyMeta(o._meta)},identity:requiredString(o.identity,"USER MCP server.identity"),logicalName:l,serverName:p,transport:{headers:parseUserMcpStringRecord(d.headers,"USER MCP remote headers"),type:d.type,url:u}}}throw new Error("CodeBuddy host response has unsupported USER MCP transport")});return{errors:n,generation:e.generation,servers:a,version:1}}c(parseUserMcpSnapshot,"parseUserMcpSnapshot");export function parsePluginMcpResolveResult(e){let t;try{t=Buffer.byteLength(JSON.stringify(e))}catch{throw new Error("CodeBuddy host response has invalid Plugin MCP snapshot")}if(t>MAX_PLUGIN_MCP_SNAPSHOT_BYTES)throw new Error("CodeBuddy host response exceeds the Plugin MCP snapshot limit");const n=S(e);if(n===void 0)throw new Error("CodeBuddy host response has invalid Plugin MCP snapshot");return structuredClone(n)}c(parsePluginMcpResolveResult,"parsePluginMcpResolveResult");export const MANAGED_AUTH_LOGIN_STATES=new Set(["pending","succeeded","failed","cancelled","timed_out"]);export function parseManagedAuthSnapshot(e){if(!i(e)||typeof e.authenticated!="boolean")throw new Error("CodeBuddy management response has invalid auth snapshot data");let t=null;if(e.account!==null){if(!i(e.account))throw new Error("CodeBuddy management response has invalid auth.account data");t={id:requiredString(e.account.id,"auth.account.id"),accountType:requiredString(e.account.accountType,"auth.account.accountType"),...optionalString(e.account.avatarUrl,"auth.account.avatarUrl")?{avatarUrl:e.account.avatarUrl}:{},...optionalString(e.account.displayName,"auth.account.displayName")?{displayName:e.account.displayName}:{},...optionalString(e.account.department,"auth.account.department")?{department:e.account.department}:{},...optionalString(e.account.enterpriseId,"auth.account.enterpriseId")?{enterpriseId:e.account.enterpriseId}:{},...optionalString(e.account.enterpriseName,"auth.account.enterpriseName")?{enterpriseName:e.account.enterpriseName}:{},...optionalString(e.account.idp,"auth.account.idp")?{idp:e.account.idp}:{},...optionalString(e.account.oneidAccountId,"auth.account.oneidAccountId")?{oneidAccountId:e.account.oneidAccountId}:{}}}if(e.authenticated!==(t!==null))throw new Error("CodeBuddy management response has inconsistent auth state");return{account:t,authenticated:e.authenticated}}c(parseManagedAuthSnapshot,"parseManagedAuthSnapshot");export function parseManagedAuthCredentialProjection(e){if(!i(e)||!i(e.account)||!i(e.credential))throw new Error("CodeBuddy management response has invalid auth credential projection");const t={id:requiredString(e.account.id,"auth.credential.account.id"),accountType:requiredString(e.account.accountType,"auth.credential.account.accountType"),...optionalString(e.account.avatarUrl,"auth.credential.account.avatarUrl")?{avatarUrl:e.account.avatarUrl}:{},...optionalString(e.account.department,"auth.credential.account.department")?{department:e.account.department}:{},...optionalString(e.account.displayName,"auth.credential.account.displayName")?{displayName:e.account.displayName}:{},...optionalString(e.account.enterpriseId,"auth.credential.account.enterpriseId")?{enterpriseId:e.account.enterpriseId}:{},...optionalString(e.account.enterpriseName,"auth.credential.account.enterpriseName")?{enterpriseName:e.account.enterpriseName}:{},...optionalString(e.account.idp,"auth.credential.account.idp")?{idp:e.account.idp}:{},...optionalString(e.account.oneidAccountId,"auth.credential.account.oneidAccountId")?{oneidAccountId:e.account.oneidAccountId}:{}},n=requiredString(e.credential.accessToken,"auth.credential.accessToken"),s=optionalString(e.credential.domain,"auth.credential.domain")?e.credential.domain:void 0;if(e.credential.type==="api_key")return{account:t,credential:{accessToken:n,...s?{domain:s}:{},type:"api_key"}};if(e.credential.type!=="bearer")throw new Error("CodeBuddy management response has invalid auth credential type");return{account:t,credential:{accessToken:n,...s?{domain:s}:{},type:"bearer",...e.credential.expiresAt===void 0?{}:{expiresAt:isoTimestamp(e.credential.expiresAt,"auth.credential.expiresAt")}}}}c(parseManagedAuthCredentialProjection,"parseManagedAuthCredentialProjection");export function parseManagedAuthLogin(e){if(!i(e)||!MANAGED_AUTH_LOGIN_STATES.has(e.state))throw new Error("CodeBuddy management response has invalid auth login data");if(e.cancelled!==void 0&&typeof e.cancelled!="boolean")throw new Error("CodeBuddy management response has invalid auth login cancelled value");if(typeof e.settled!="boolean")throw new Error("CodeBuddy management response has invalid auth login settlement");return{createdAt:isoTimestamp(e.createdAt,"auth.login.createdAt"),expiresAt:isoTimestamp(e.expiresAt,"auth.login.expiresAt"),loginId:requiredString(e.loginId,"auth.login.loginId"),methodId:requiredString(e.methodId,"auth.login.methodId"),settled:e.settled,state:e.state,...optionalString(e.authUrl,"auth.login.authUrl")?{authUrl:e.authUrl}:{},...e.cancelled===void 0?{}:{cancelled:e.cancelled},...e.completedAt===void 0?{}:{completedAt:isoTimestamp(e.completedAt,"auth.login.completedAt")}}}c(parseManagedAuthLogin,"parseManagedAuthLogin");export function stringArray(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}c(stringArray,"stringArray");export function pluginInterface(e){const t=i(e.author)?e.author:void 0,n=i(e.homepage)?e.homepage.url:e.homepage;return{capabilities:stringArray(e.features),category:nullableString(e.category,"plugin.category"),description:nullableString(e.description,"plugin.description"),developerName:nullableString(t?.name,"plugin.author.name"),displayName:requiredString(e.name,"plugin.name"),websiteUrl:nullableString(n,"plugin.homepage")}}c(pluginInterface,"pluginInterface");export function projectPluginSummary(e,t){const n=requiredString(e.name,"plugin.name"),s=typeof e.installed=="boolean"?e.installed:typeof e.installedPath=="string"&&e.installedPath.length>0,r=optionalString(e.status,"plugin.status"),a=typeof e.enabled=="boolean"?e.enabled:r==="enabled",o=nullableString(e.resolvedVersion??e.version,"plugin.version");return{enabled:a,id:`${n}@${t.id}`,installed:s,interface:pluginInterface(e),keywords:stringArray(e.keywords),localVersion:s?o:null,name:n,source:pluginSource(e,t),version:o}}c(projectPluginSummary,"projectPluginSummary");export function projectSkill(e){if(typeof e=="string")return{description:"",enabled:!0,name:f.basename(e),path:e,shortDescription:null};if(!i(e))return;const t=optionalString(e.name,"plugin.skill.name");return t?{description:optionalString(e.description,"plugin.skill.description")??"",enabled:e.enabled!==!1,name:t,path:nullableString(e.path,"plugin.skill.path"),shortDescription:nullableString(e.shortDescription,"plugin.skill.shortDescription")}:void 0}c(projectSkill,"projectSkill");export const HOOK_EVENT_NAMES=new Map([["PreToolUse","preToolUse"],["PostToolUse","postToolUse"],["Notification","notification"],["UserPromptSubmit","userPromptSubmit"],["Stop","stop"],["SubagentStop","subagentStop"],["PreCompact","preCompact"],["SessionStart","sessionStart"],["SessionEnd","sessionEnd"],["WorktreeCreate","worktreeCreate"],["WorktreeRemove","worktreeRemove"],["PostToolUseFailure","postToolUseFailure"],["SubagentStart","subagentStart"],["StopFailure","stopFailure"],["PostCompact","postCompact"],["ConfigChange","configChange"],["InstructionsLoaded","instructionsLoaded"],["PermissionRequest","permissionRequest"],["PermissionDenied","permissionDenied"],["Elicitation","elicitation"],["ElicitationResult","elicitationResult"],["TaskCreated","taskCreated"],["TaskCompleted","taskCompleted"],["TeammateIdle","teammateIdle"],["Setup","setup"],["FileChanged","fileChanged"],["CwdChanged","cwdChanged"],["FinalStop","finalStop"]]),PUBLIC_HOOK_EVENT_NAMES=new Set(HOOK_EVENT_NAMES.values());export function projectHooks(e){return Array.isArray(e)?e.map((t,n)=>{if(!i(t))throw new Error(`CodeBuddy management response has invalid plugin.hooks.${n}`);const s=requiredString(t.eventName,`plugin.hooks.${n}.eventName`),r=HOOK_EVENT_NAMES.get(s)??(PUBLIC_HOOK_EVENT_NAMES.has(s)?s:void 0);if(!r)throw new Error(`CodeBuddy management response has invalid plugin.hooks.${n}.eventName`);return{eventName:r,key:requiredString(t.key,`plugin.hooks.${n}.key`)}}):i(e)?Object.keys(e).flatMap(t=>{const n=HOOK_EVENT_NAMES.get(t)??(PUBLIC_HOOK_EVENT_NAMES.has(t)?t:void 0);return n?[{eventName:n,key:t}]:[]}):[]}c(projectHooks,"projectHooks");export function projectMcpServers(e){if(e==null||typeof e=="string")return[];if(Array.isArray(e))return[...new Set(e.map((t,n)=>requiredString(t,`plugin.mcpServers.${n}`)))];if(!i(e))throw new Error("CodeBuddy management response has invalid plugin.mcpServers");return Object.keys(e).map((t,n)=>requiredString(t,`plugin.mcpServers.${n}`))}c(projectMcpServers,"projectMcpServers");export function componentItems(e,t){if(e==null)return[];if(Array.isArray(e))return e;if(typeof e=="string")return[];if(i(e))return[e];throw new Error(`CodeBuddy management response has invalid ${t}`)}c(componentItems,"componentItems");export function projectCommands(e){return componentItems(e,"plugin.commands").flatMap((t,n)=>{if(typeof t=="string")return[];if(!i(t))throw new Error(`CodeBuddy management response has invalid plugin.commands.${n}`);return[{argumentHint:nullableString(t.argumentHint??t["argument-hint"],`plugin.commands.${n}.argumentHint`),description:nullableString(t.description,`plugin.commands.${n}.description`),name:requiredString(t.name,`plugin.commands.${n}.name`)}]})}c(projectCommands,"projectCommands");export function projectAgents(e){return componentItems(e,"plugin.agents").flatMap((t,n)=>{if(typeof t=="string")return[];if(!i(t))throw new Error(`CodeBuddy management response has invalid plugin.agents.${n}`);return[{description:nullableString(t.description,`plugin.agents.${n}.description`),name:requiredString(t.name,`plugin.agents.${n}.name`)}]})}c(projectAgents,"projectAgents");export function projectNamedServers(e,t){if(e==null)return[];if(typeof e=="string")return[];if(Array.isArray(e))return[...new Set(e.map((n,s)=>{if(typeof n=="string")return requiredString(n,`${t}.${s}`);if(i(n))return requiredString(n.name,`${t}.${s}.name`);throw new Error(`CodeBuddy management response has invalid ${t}.${s}`)}))];if(!i(e))throw new Error(`CodeBuddy management response has invalid ${t}`);return Object.keys(e).map((n,s)=>requiredString(n,`${t}.${s}`))}c(projectNamedServers,"projectNamedServers");export function projectOutputStyles(e){return componentItems(e,"plugin.outputStyles").flatMap((t,n)=>{if(typeof t=="string")return[];if(!i(t))throw new Error(`CodeBuddy management response has invalid plugin.outputStyles.${n}`);return[{description:nullableString(t.description,`plugin.outputStyles.${n}.description`),name:requiredString(t.name,`plugin.outputStyles.${n}.name`)}]})}c(projectOutputStyles,"projectOutputStyles");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tencent-ai/agent-harness",
|
|
3
|
-
"version": "0.2.0-beta.
|
|
3
|
+
"version": "0.2.0-beta.11",
|
|
4
4
|
"description": "Standalone JSON-RPC agent harness backed by CodeBuddy Code",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -225,17 +225,17 @@
|
|
|
225
225
|
"@tencent-ai/sandbox-cli-linux-arm64": "5.9.0-beta.3",
|
|
226
226
|
"@tencent-ai/sandbox-cli-linux-x64": "5.9.0-beta.3",
|
|
227
227
|
"@tencent-ai/sandbox-cli-win32-x64": "5.9.0-beta.3",
|
|
228
|
-
"@tencent-ai/agent-harness-darwin-arm64": "0.2.0-beta.
|
|
229
|
-
"@tencent-ai/agent-harness-darwin-x64": "0.2.0-beta.
|
|
230
|
-
"@tencent-ai/agent-harness-linux-arm64": "0.2.0-beta.
|
|
231
|
-
"@tencent-ai/agent-harness-linux-arm64-musl": "0.2.0-beta.
|
|
232
|
-
"@tencent-ai/agent-harness-linux-x64": "0.2.0-beta.
|
|
233
|
-
"@tencent-ai/agent-harness-linux-x64-musl": "0.2.0-beta.
|
|
234
|
-
"@tencent-ai/agent-harness-win32-x64": "0.2.0-beta.
|
|
228
|
+
"@tencent-ai/agent-harness-darwin-arm64": "0.2.0-beta.11",
|
|
229
|
+
"@tencent-ai/agent-harness-darwin-x64": "0.2.0-beta.11",
|
|
230
|
+
"@tencent-ai/agent-harness-linux-arm64": "0.2.0-beta.11",
|
|
231
|
+
"@tencent-ai/agent-harness-linux-arm64-musl": "0.2.0-beta.11",
|
|
232
|
+
"@tencent-ai/agent-harness-linux-x64": "0.2.0-beta.11",
|
|
233
|
+
"@tencent-ai/agent-harness-linux-x64-musl": "0.2.0-beta.11",
|
|
234
|
+
"@tencent-ai/agent-harness-win32-x64": "0.2.0-beta.11"
|
|
235
235
|
},
|
|
236
236
|
"devDependencies": {
|
|
237
237
|
"@anthropic-ai/sandbox-runtime": "0.0.17",
|
|
238
|
-
"@genie/agent-cli": "2.
|
|
238
|
+
"@genie/agent-cli": "2.163.0",
|
|
239
239
|
"@genie/agent-client-protocol": "0.0.0",
|
|
240
240
|
"@genie/at-rest-crypto": "0.0.0",
|
|
241
241
|
"@genie/authentication": "0.0.0",
|