buckyos 0.7.208 → 0.7.209
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/cli/dist/cli.mjs +602 -179
- package/cli/dist/cli.mjs.map +1 -1
- package/cli/modules/ai.ts +460 -23
- package/cli/modules/aiws.ts +1 -1
- package/cli/version.ts +1 -1
- package/dist/{aicc-67851c41.mjs → aicc-286ba457.mjs} +7 -5
- package/dist/aicc-286ba457.mjs.map +1 -0
- package/dist/aicc-342f2659.js +2 -0
- package/dist/aicc-342f2659.js.map +1 -0
- package/dist/aicc_client.d.ts +623 -288
- package/dist/aicc_client.d.ts.map +1 -1
- package/dist/{aiws_write-83ddc6cc.mjs → aiws_write-5b542439.mjs} +203 -134
- package/dist/aiws_write-5b542439.mjs.map +1 -0
- package/dist/aiws_write-a0769003.js +13 -0
- package/dist/aiws_write-a0769003.js.map +1 -0
- package/dist/browser.cjs +1 -1
- package/dist/browser.mjs +85 -78
- package/dist/{content_objid-76434848.mjs → content_objid-09031ce1.mjs} +2 -2
- package/dist/{content_objid-76434848.mjs.map → content_objid-09031ce1.mjs.map} +1 -1
- package/dist/{content_objid-addf9e2b.js → content_objid-6342d0ba.js} +2 -2
- package/dist/{content_objid-addf9e2b.js.map → content_objid-6342d0ba.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +85 -78
- package/dist/node.cjs +1 -1
- package/dist/node.mjs +84 -77
- package/dist/{openai-ae2978de.mjs → openai-1c0d8341.mjs} +2 -2
- package/dist/{openai-ae2978de.mjs.map → openai-1c0d8341.mjs.map} +1 -1
- package/dist/{openai-f560d518.js → openai-7aa4ffbf.js} +2 -2
- package/dist/{openai-f560d518.js.map → openai-7aa4ffbf.js.map} +1 -1
- package/dist/{site_manager-604ee369.mjs → site_manager-4f1940eb.mjs} +4 -4
- package/dist/{site_manager-604ee369.mjs.map → site_manager-4f1940eb.mjs.map} +1 -1
- package/dist/{site_manager-70710895.js → site_manager-ca22ffbd.js} +2 -2
- package/dist/{site_manager-70710895.js.map → site_manager-ca22ffbd.js.map} +1 -1
- package/dist/xllm/core/run.d.ts.map +1 -1
- package/dist/xllm/providers/aicc.d.ts +7 -3
- package/dist/xllm/providers/aicc.d.ts.map +1 -1
- package/dist/xllm.cjs +1 -1
- package/dist/xllm.mjs +4 -4
- package/dist/xllm_deno.cjs +1 -1
- package/dist/xllm_deno.mjs +3 -3
- package/dist/xllm_dev.cjs +1 -1
- package/dist/xllm_dev.mjs +2 -2
- package/package.json +1 -1
- package/dist/aicc-67851c41.mjs.map +0 -1
- package/dist/aicc-ccb36ef7.js +0 -2
- package/dist/aicc-ccb36ef7.js.map +0 -1
- package/dist/aiws_write-825bb6ba.js +0 -13
- package/dist/aiws_write-825bb6ba.js.map +0 -1
- package/dist/aiws_write-83ddc6cc.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../../../src/xllm/core/run.ts"],"names":[],"mappings":"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
|
|
1
|
+
{"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../../../src/xllm/core/run.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EACV,SAAS,EAAE,SAAS,EAAuB,UAAU,EAAE,eAAe,EAAE,cAAc,EAAkB,aAAa,EAA6B,kBAAkB,EAAE,kBAAkB,EAAE,WAAW,EAAE,SAAS,EAChN,eAAe,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,cAAc,EAC/G,SAAS,EAAE,WAAW,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAChF,MAAM,SAAS,CAAA;AAChB,OAAO,EAAE,UAAU,EAAE,sBAAsB,EAAE,MAAM,QAAQ,CAAA;AAO3D,OAAO,EAAE,WAAW,EAAyB,MAAM,UAAU,CAAA;AAG7D,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAchD,OAAO,KAAK,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,WAAW,CAAA;AACzD,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAA;AACpE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAA;AAKhE,eAAO,MAAM,mBAAmB,gBAAgB,CAAA;AAwBhD,eAAO,MAAM,wBAAwB,EAAE,kBAAqF,CAAA;AAC5H,eAAO,MAAM,yBAAyB,EAAE,kBAAwF,CAAA;AAEhI,6GAA6G;AAC7G,MAAM,WAAW,QAAQ;IACvB,GAAG,EAAE,SAAS,CAAA;IACd,OAAO,EAAE,YAAY,CAAA;IACrB,KAAK,EAAE,QAAQ,CAAA;IACf,QAAQ,CAAC,EAAE,WAAW,CAAA;IACtB,SAAS,CAAC,EAAE,SAAS,CAAA;IACrB,iFAAiF;IACjF,kBAAkB,CAAC,EAAE,kBAAkB,GAAG,MAAM,GAAG,KAAK,CAAA;IACxD,qEAAqE;IACrE,YAAY,CAAC,EAAE,kBAAkB,CAAA;IACjC,mFAAmF;IACnF,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,6EAA6E;IAC7E,WAAW,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAAA;IACrE,+FAA+F;IAC/F,aAAa,CAAC,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;IACjD,8FAA8F;IAC9F,KAAK,CAAC,EAAE,mBAAmB,CAAA;CAC5B;AASD,kGAAkG;AAClG,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAA;IACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAA;IAChC,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAA;IAC3B,gBAAgB;IAChB,QAAQ,CAAC,OAAO,EAAE,cAAc,CAAA;CACjC;AAED,8EAA8E;AAC9E,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAA;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAA;IAChC,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAA;IAC3B,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAA;IAC3B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,eAAe,EAAE,SAAS,EAAE,CAAA;IACrC,QAAQ,CAAC,aAAa,EAAE,SAAS,EAAE,CAAA;IACnC,QAAQ,CAAC,SAAS,CAAC,EAAE,aAAa,CAAA;IAClC,gBAAgB;IAChB,QAAQ,CAAC,OAAO,EAAE,cAAc,CAAA;CACjC;AAoBD,mFAAmF;AACnF,wBAAgB,aAAa,CAAC,GAAG,EAAE,eAAe,GAAG,UAAU,CAa9D;AAED,2GAA2G;AAC3G,wBAAgB,UAAU,CAAC,GAAG,EAAE,eAAe,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EACvH,KAAK,EAAE,SAAS,EAAE,EAAE,MAAM,EAAE,OAAO,GAAG,iBAAiB,CA8BxD;AAQD,2DAA2D;AAC3D,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,kBAAkB,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,QAOhH;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,WAAW,EAAE,QAAQ,EAAE,kBAAkB,EACrH,MAAM,EAAE,kBAAkB,EAAE,SAAS,EAAE,SAAS,EAAE,KAAK,EAAE,cAAc,EAAE,IAAI,EAAE,OAAO;;;;;EAiBvF;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,CAAC,SAAS,EAAE,qBAAqB,GAAG,cAAc,CAAC,GAAG,MAAM,CAItH;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,IAAI,CAAC,SAAS,EAAE,qBAAqB,GAAG,cAAc,CAAC,GAC1H;IAAE,MAAM,EAAE,SAAS,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAA;CAAE,CAe5D;AAED,qBAAa,QAAQ;IACnB;;;;OAIG;IACH,MAAM,CAAC,OAAO,CAAC,UAAU,EAAE,SAAS,GAAG,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,aAAa,EAAE,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC,YAAY,CAAC;IAIpJ;;;;;;OAMG;WACU,aAAa,CAAC,UAAU,EAAE,SAAS,GAAG,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC,UAAU,CAAC;CA2CvI;AAED,MAAM,WAAW,UAAU;IACzB,MAAM,EAAE,SAAS,CAAA;IACjB,MAAM,EAAE,SAAS,CAAA;CAClB;AAED,MAAM,WAAW,YAAY;IAC3B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,mBAAmB,CAAC,EAAE,MAAM,CAAA;IAC5B,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B;AAED,MAAM,MAAM,WAAW,GAAG;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,MAAM,EAAE,SAAS,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,KAAK,CAAC;IAAC,GAAG,EAAE,OAAO,CAAA;CAAE,CAAA;AAEjG,0FAA0F;AAC1F,qBAAa,eAAe;IAC1B,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,CAAA;IAC9C,gBAAgB,CAAC,MAAM,EAAE;QAAE,SAAS,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;QAAC,MAAM,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,GAAG,SAAS,CAAA;IAElG,SAAS,CAAC,MAAM,EAAE,MAAM;IAKxB,MAAM,CAAC,MAAM,EAAE,MAAM;CAItB;AAED,MAAM,WAAW,YAAY;IAC3B,0DAA0D;IAC1D,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,EAAE,CAAA;IAC5B,uEAAuE;IACvE,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED,kCAAkC;AAClC,qBAAa,OAAO;IAiBhB,OAAO,CAAC,QAAQ,CAAC,KAAK;IAEtB,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAnB1B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB,OAAO,CAAC,MAAM,CAAW;IACzB,OAAO,CAAC,GAAG,CAAwB;IACnC,OAAO,CAAC,aAAa,CAAgC;IACrD,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAwB;IACzD,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAkB;IACtC,OAAO,CAAC,YAAY,CAAI;IACxB,OAAO,CAAC,IAAI,CAAqB;IACjC,OAAO,CAAC,WAAW,CAAqB;IACxC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAgB;IAC1C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,OAAO,CAAC,eAAe,CAAa;IACpC,OAAO,CAAC,SAAS,CAA2B;IAC5C,OAAO,CAAC,aAAa,CAAa;IAElC,OAAO;IAwCP,sGAAsG;WACzF,KAAK,CAAC,IAAI,EAAE,UAAU,GAAG,YAAY,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,GAAE,YAAiB,GAAG,OAAO,CAAC,OAAO,CAAC;IA2CjH;;;;OAIG;WACU,MAAM,CAAC,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC,WAAW,CAAC;IAyE/G,8BAA8B;IAC9B,aAAa,IAAI,SAAS;IAI1B,WAAW,IAAI,eAAe;IAI9B;;;;OAIG;IACG,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ9C,iGAAiG;IAC3F,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAM9B,sDAAsD;IAChD,OAAO,IAAI,OAAO,CAAC,UAAU,CAAC;YAatB,aAAa;YA+Cb,aAAa;IA+E3B;;;;OAIG;YACW,cAAc;YA2Cd,mBAAmB;IAsBjC,qHAAqH;YACvG,YAAY;YAsDZ,kBAAkB;YAuClB,WAAW;IASzB,gBAAgB;IAChB,MAAM,CAAC,GAAG,EAAE,UAAU;IAKtB,OAAO,CAAC,QAAQ;IAMhB,OAAO,CAAC,OAAO;YAID,MAAM;YAaN,MAAM;IASpB,OAAO,CAAC,IAAI;CAGb;AAED,wBAAgB,UAAU,CAAC,CAAC,EAAE,SAAS,GAAG,OAAO,CAEhD;AA0DD,mHAAmH;AACnH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,kBAAkB,4CAUxD;AAuBD,iGAAiG;AACjG,wBAAgB,aAAa,CAAC,GAAG,EAAE,eAAe,GAAG,cAAc,CAqClE;AAED,OAAO,EAAE,sBAAsB,EAAE,CAAA"}
|
|
@@ -2,7 +2,8 @@ import type { AiccClient, AiccError } from '../../aicc_client';
|
|
|
2
2
|
import type { AiResponse, JsonValue, LlmClient, LlmInferenceRequest, ProviderFailure } from '../core/types';
|
|
3
3
|
import { LLMComputeException } from '../core/errors';
|
|
4
4
|
export declare const REFUSED_QUOTA_EXHAUSTED = "quota_exhausted";
|
|
5
|
-
|
|
5
|
+
/** The user's AI Credit balance is used up (not a Provider account balance). */
|
|
6
|
+
export declare const REFUSED_CREDIT_INSUFFICIENT = "credit_insufficient";
|
|
6
7
|
export declare const REFUSED_RESOURCE_NOT_PERMITTED = "resource_not_permitted";
|
|
7
8
|
export declare const REFUSED_ATTRIBUTION_UNAVAILABLE = "attribution_unavailable";
|
|
8
9
|
/** The service refused the caller's credentials: sign in again, then resume. */
|
|
@@ -13,10 +14,13 @@ export declare function anyJsonObjectSchema(): JsonValue;
|
|
|
13
14
|
export declare function aiccProviderFailure(error: Partial<AiccError>): ProviderFailure | undefined;
|
|
14
15
|
/** A failed AICC call (a rejected kRPC call) as a provider error. */
|
|
15
16
|
export declare function providerErrorFromRpc(context: string, err: unknown): LLMComputeException;
|
|
16
|
-
/** `LlmClient` over the page's AICC client. */
|
|
17
|
+
/** `LlmClient` over the page's AICC client. `route_group`: the routing group of the host's session, sent with routed requests. */
|
|
17
18
|
export declare class AiccLlmClient implements LlmClient {
|
|
18
19
|
private readonly client;
|
|
19
|
-
|
|
20
|
+
private readonly options;
|
|
21
|
+
constructor(client: AiccClient, options?: {
|
|
22
|
+
route_group?: string;
|
|
23
|
+
});
|
|
20
24
|
infer(req: LlmInferenceRequest): Promise<AiResponse>;
|
|
21
25
|
}
|
|
22
26
|
//# sourceMappingURL=aicc.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aicc.d.ts","sourceRoot":"","sources":["../../../src/xllm/providers/aicc.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EACV,UAAU,EAAE,SAAS,EAEtB,MAAM,mBAAmB,CAAA;AAG1B,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAA;AAC3G,OAAO,EAAE,mBAAmB,EAAiB,MAAM,gBAAgB,CAAA;AAGnE,eAAO,MAAM,uBAAuB,oBAAoB,CAAA;AACxD,eAAO,MAAM,
|
|
1
|
+
{"version":3,"file":"aicc.d.ts","sourceRoot":"","sources":["../../../src/xllm/providers/aicc.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EACV,UAAU,EAAE,SAAS,EAEtB,MAAM,mBAAmB,CAAA;AAG1B,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAA;AAC3G,OAAO,EAAE,mBAAmB,EAAiB,MAAM,gBAAgB,CAAA;AAGnE,eAAO,MAAM,uBAAuB,oBAAoB,CAAA;AACxD,gFAAgF;AAChF,eAAO,MAAM,2BAA2B,wBAAwB,CAAA;AAChE,eAAO,MAAM,8BAA8B,2BAA2B,CAAA;AACtE,eAAO,MAAM,+BAA+B,4BAA4B,CAAA;AACxE,gFAAgF;AAChF,eAAO,MAAM,mBAAmB,gBAAgB,CAAA;AAIhD,yGAAyG;AACzG,wBAAgB,mBAAmB,IAAI,SAAS,CAE/C;AAMD,+EAA+E;AAC/E,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,CAAC,SAAS,CAAC,GAAG,eAAe,GAAG,SAAS,CAQ1F;AAED,qEAAqE;AACrE,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,GAAG,mBAAmB,CAoBvF;AAWD,kIAAkI;AAClI,qBAAa,aAAc,YAAW,SAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,MAAM;IAAc,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAA5C,MAAM,EAAE,UAAU,EAAmB,OAAO,GAAE;QAAE,WAAW,CAAC,EAAE,MAAM,CAAA;KAAO;IAElG,KAAK,CAAC,GAAG,EAAE,mBAAmB,GAAG,OAAO,CAAC,UAAU,CAAC;CAkE3D"}
|
package/dist/xllm.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./aicc-ccb36ef7.js"),t=require("./site_manager-70710895.js"),o=require("./did_object_client-27835522.js");require("./krpc_client-26c2dc8b.js"),require("./object_url-88047ee2.js"),require("./ndn_types-5b138882.js");const r="site",n=/^[A-Za-z0-9_-]{1,64}$/;function s(o,r){return(o??[]).map((o=>{if("named"!==o.kind)throw e.XllmError.capability(`${r}: \`${t.describeToolSource(o)}\` is not available in a site runtime; only the page's tools can be named`);return o.name}))}class i extends Error{constructor(e,t){super(t),this.name="CommandArgsError",this.code=e}}function a(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function c(e){return e.property??e.name.split("-").join("_")}function l(e){const t=e.slice(2),o=t.indexOf("=");return o<0?{name:t}:{name:t.slice(0,o),inlineValue:t.slice(o+1)}}function u(e,t,o){if(void 0!==o.inlineValue){if(!o.inlineValue)throw new i("MISSING_ARGUMENT",`--${o.name} requires a value`);return{value:o.inlineValue,consumed:1}}const r=e[t+1];if(void 0===r||r.startsWith("--"))throw new i("MISSING_ARGUMENT",`--${o.name} requires a value`);return{value:r,consumed:2}}function p(e,t,o){if("string"===e)return t;const r=Number(t);if(!Number.isFinite(r)||"integer"===e&&!Number.isInteger(r))throw new i("INVALID_ARGUMENT",`--${o} requires a ${e}`);return r}function d(e,t,o,r){const n=t[o];if(!n)throw new i("TOO_MANY_ARGUMENTS",`unexpected positional argument: ${r}`);return e[n.name]=r,o+1}function m(e){const t=[];let o="",r=null,n=!1,s=!1;for(const i of e)n?(o+=i,n=!1,s=!0):"\\"!==i||"single"===r?"single"!==r?"double"!==r?"'"!==i?'"'!==i?/\s/.test(i)?s&&(t.push(o),o="",s=!1):(o+=i,s=!0):(r="double",s=!0):(r="single",s=!0):'"'===i?r=null:o+=i:"'"===i?r=null:o+=i:(n=!0,s=!0);if(n)throw new i("INVALID_COMMAND_LINE","unfinished escape sequence");if(r)throw new i("INVALID_COMMAND_LINE",`unterminated ${r} quote`);return s&&t.push(o),t}function f(e,t,o){var r;if(t.enum&&!t.enum.some((t=>Object.is(t,e))))throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be one of ${t.enum.join(", ")}`);if("object"!==t.type)if("array"!==t.type)if("string"!==t.type){if("boolean"===t.type&&"boolean"!=typeof e)throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be a boolean`);if("integer"===t.type&&(!Number.isInteger(e)||"number"!=typeof e))throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be an integer`);if("number"===t.type&&"number"!=typeof e)throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be a number`)}else{if("string"!=typeof e)throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be a string`);if(void 0!==t.minLength&&e.length<t.minLength)throw new i("SCHEMA_VALIDATION_FAILED",`${o} is too short`)}else{if(!Array.isArray(e))throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be an array`);const r=t.items;r&&e.forEach(((e,t)=>f(e,r,`${o}[${t}]`)))}else{if(!e||"object"!=typeof e||Array.isArray(e))throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be an object`);const n=e;for(const e of t.required??[])if(!a(n,e))throw new i("SCHEMA_VALIDATION_FAILED",`${o}.${e} is required`);if(!1===t.additionalProperties)for(const e of Object.keys(n))if(!a(t.properties??{},e))throw new i("SCHEMA_VALIDATION_FAILED",`${o}.${e} is not allowed`);for(const[e,s]of Object.entries(n)){const n=null==(r=t.properties)?void 0:r[e];n&&f(s,n,`${o}.${e}`)}}}const g=["read_only","idempotent_write","write","destructive","admin"],h="xcall <object> <action> [--params <json>] [key=value ...] [--key=value ...]",_=65536,x=/[|;&><`$]/;function y(e){throw new Error(e)}function T(e,t){const o=e.trim();o||y("uri is empty");const r=/^[A-Za-z][A-Za-z0-9+.-]*:/.test(o);let n,s;try{n=r?new URL(o):new URL(o.replace(/^\/+/,""),"site://page/")}catch{y(`invalid uri \`${o}\``)}r?(s=`${n.protocol.slice(0,-1).toLowerCase()}://${n.host.toLowerCase()}`,t.has(s)||y(`uri \`${o}\` is not a resource of this page (absolute URIs are limited to the declared ones)`)):"site:"===n.protocol&&"page"===n.host||y(`uri \`${o}\` is not a resource of this page`);const i=[];for(const c of n.pathname.split("/")){if(""===c)continue;let e;try{e=decodeURIComponent(c)}catch{y(`invalid uri \`${o}\``)}(".."===e||"."===e||e.includes("/")||e.includes("\\"))&&y(`uri \`${o}\` is not a resource of this page`),i.push(e)}const a=(s?`${s}/`:"")+i.join("/")+(n.search||"");return{origin:s,segments:i,query:n.searchParams,text:a}}function S(e,t,o){if(e.origin!==t||e.segments.length!==o.length)return;const r={};for(let n=0;n<o.length;n++){const t=e.segments[n];if(t.startsWith("{")&&t.endsWith("}"))r[t.slice(1,-1)]=o[n];else if(t!==o[n])return}return r}function E(e){if(null==e)return"";if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function w(t){if(e.isObject(t)&&"content"in t&&Object.keys(t).every((e=>"content"===e||"version"===e))){const e=t.version;return{text:E(t.content),version:"string"==typeof e?e:void 0===e?void 0:String(e)}}return{text:E(t)}}function b(e,o){if(t.utf8Length(e)<=o)return{text:e,clipped:!1};let r="",n=0;for(const s of e){const e=t.utf8Length(s);if(n+e>o)break;r+=s,n+=e}return{text:r,clipped:!0}}function O(e,o=1,r){const n=e.split("\n"),s=Math.max(1,Math.floor(o));if(s>n.length&&(1!==s||1!==n.length))return`[offset ${s} is past the end: ${n.length} lines]`;const i=void 0===r?n.length:Math.max(1,Math.floor(r)),a=[];let c=0,l=s-1;for(;l<n.length&&a.length<i;l++){const e=t.utf8Length(n[l])+1;if(a.length>0&&c+e>_)break;a.push(n[l]),c+=e}let u=a.join("\n");return 1===a.length&&t.utf8Length(u)>_&&(u=b(u,_).text+" …"),l<n.length&&(u+=`\n[lines ${s}–${l} of ${n.length}; read on with offset=${l+1}]`),u}function A(e){const t=e.trim();if("true"===t)return!0;if("false"===t)return!1;if("null"===t)return null;if(/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(t))return Number(t);if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t)}catch{return t}return t}const R=["config","route-config","session-id","session_id","idempotency-key","idempotency_key","confirm-token","confirm_token","trace-id","trace_id"];function I(t){let o,r,n={};const s={},i=[],a=(e,t)=>{try{return JSON.parse(e)}catch(o){y(`invalid \`${t}\` JSON value \`${e}\`: ${o instanceof Error?o.message:String(o)}\nusage: ${h}`)}},c=e=>y(`unsupported flag \`${e}\` (routing and confirmation are the page's)\nusage: ${h}`);for(let e=0;e<t.length;e++){const l=t[e];if("--params"===l){const o=t[++e];void 0===o&&y(`missing value for --params\nusage: ${h}`),n=a(o,"--params")}else if(l.startsWith("--")){const e=l.indexOf("=");e<0&&c(l);const t=l.slice(2,e),o=l.slice(e+1);"params"===t?n=a(o,"--params"):!t.trim()||t.startsWith("-")||R.includes(t)?c(l):s[t]=A(o)}else if(l.includes("=")){const e=l.indexOf("="),t=l.slice(0,e),i=l.slice(e+1);"object"===t?o=i:"action"===t?r=i:"params"===t?n=a(i,"params"):R.includes(t)?c(l):s[t]=A(i)}else i.push(l)}return o=o??i[0],r=r??i[1],void 0!==i[2]&&(n=a(i[2],"params")),i.length>3&&y(`unexpected positional argument \`${i[3]}\`\nusage: ${h}`),Object.keys(s).length&&(e.isObject(n)||y(`key=value params require object params\nusage: ${h}`),n={...n,...s}),o&&r||y(`xcall needs an object and an action\nusage: ${h}`),e.isObject(n)||y(`params must be a JSON object\nusage: ${h}`),{object:o,action:r,params:n}}function $(e,t){var o;const r=[`${e} — ${t.summary}`];t.description&&r.push("",t.description);const n=(t.positionals??[]).map((e=>!1===e.required?`[${e.name}]`:`<${e.name}>`)).join(" ");r.push("",`usage: ${e}${n?` ${n}`:""}${(t.options??[]).length?" [options]":""}`);for(const s of t.positionals??[])r.push(` ${s.name} ${s.description}`);(t.options??[]).length&&r.push("options:");for(const s of t.options??[])r.push(` --${s.name}${"boolean"===s.type?"":` <${s.type}>`}${s.required?" (required)":""} ${s.description}${s.enum?` (${s.enum.join(" | ")})`:""}`);if(null==(o=t.examples)?void 0:o.length){r.push("examples:");for(const e of t.examples)r.push(` ${e}`)}return r.join("\n")}const N=(e,t)=>({type:"object",properties:e,required:t});const M="https://buckyos.org/traits/index@1";function L(t,o){return e.isObject(t)&&"string"==typeof t[o]?t[o]:""}function v(e){const t=g.indexOf(e);return t<0?g.length:t}function k(t,o,r,n){const s=[`Object: ${t}`,`Object DID: ${o.id}`],i=(o.alsoKnownAs??[]).filter((e=>e!==t));i.length&&s.push(`Also known as: ${i.join(", ")}`);for(const[e,c]of[["Title","title"],["Description","description"]]){const t=L(r,c);t&&s.push(`${e}: ${t}`)}for(const[c,l]of[["Properties","properties"],["Actions","actions"],["Events","events"]]){const t=e.isObject(r)?r[l]:void 0;if(e.isObject(t)&&0!==Object.keys(t).length){s.push(`${c}:`);for(const e of Object.keys(t).sort()){const o=t[e];let r=`- ${e}`;const n=L(o,"description");n&&(r+=`: ${n}`);const i=L(o,"x-buckyos:risk");i&&(r+=` (risk: ${i})`),s.push(r)}}}const a=Object.keys(n);if(a.length){s.push("Summary:");for(const e of a)s.push(`- ${e}:`,JSON.stringify(n[e],null,2))}return s.join("\n")}function j(t){const o=e.isObject(t)?t["x-buckyos:traits"]:void 0;return Array.isArray(o)&&o.includes(M)}const C="xllm-runs",D="records",U="snapshots";function H(e){return new Promise(((t,o)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>o(e.error)}))}function P(e){return new Promise(((t,o)=>{e.oncomplete=()=>t(),e.onerror=()=>o(e.error),e.onabort=()=>o(e.error??new Error("transaction aborted"))}))}exports.AiccLlmClient=e.AiccLlmClient,exports.LLMComputeException=e.LLMComputeException,exports.XllmError=e.XllmError,exports.aiccProviderFailure=e.aiccProviderFailure,exports.anyJsonObjectSchema=e.anyJsonObjectSchema,exports.asComputeError=e.asComputeError,exports.charCount=e.charCount,exports.computeErrorMessage=e.computeErrorMessage,exports.errorSource=e.errorSource,exports.infraRetrySafe=e.infraRetrySafe,exports.llmCorrectable=e.llmCorrectable,exports.providerError=e.providerError,exports.providerErrorFromRpc=e.providerErrorFromRpc,exports.rustTrim=e.rustTrim,exports.rustTrimEnd=e.rustTrimEnd,exports.rustTrimStart=e.rustTrimStart,exports.serdeJson=e.serdeJson,exports.AGENT_TOOL_PROTOCOL_VERSION=t.AGENT_TOOL_PROTOCOL_VERSION,exports.ByteHeuristicTokenizer=t.ByteHeuristicTokenizer,exports.DEFAULT_CONTEXT_YIELD_RATIO=t.DEFAULT_CONTEXT_YIELD_RATIO,exports.DEFAULT_LLM_TIMEOUT_SECS=t.DEFAULT_LLM_TIMEOUT_SECS,exports.DEFAULT_MAX_CONSECUTIVE_ERRORS=t.DEFAULT_MAX_CONSECUTIVE_ERRORS,exports.DEFAULT_MAX_TOOL_ITERATIONS=t.DEFAULT_MAX_TOOL_ITERATIONS,exports.DEFAULT_TASK_WAIT_MS=t.DEFAULT_TASK_WAIT_MS,exports.DEFAULT_TIMEOUT_SECS=t.DEFAULT_TIMEOUT_SECS,exports.HINT_NS_DEDUP=t.HINT_NS_DEDUP,exports.HINT_NS_ONCE=t.HINT_NS_ONCE,exports.HOST_PROMPT_SECTIONS_ALL=t.HOST_PROMPT_SECTIONS_ALL,exports.HOST_PROMPT_SECTIONS_NONE=t.HOST_PROMPT_SECTIONS_NONE,exports.LLMContext=t.LLMContext,exports.LLMContextInterruptHandle=t.LLMContextInterruptHandle,exports.LlmSummarizeCompressor=t.LlmSummarizeCompressor,exports.MAX_IMAGE_ATTACHMENT_BYTES=t.MAX_IMAGE_ATTACHMENT_BYTES,exports.MAX_INJECTIONS_PER_BOUNDARY=t.MAX_INJECTIONS_PER_BOUNDARY,exports.MAX_IN_TOOL_WAIT_MS=t.MAX_IN_TOOL_WAIT_MS,exports.MAX_TEXT_ATTACHMENT_BYTES=t.MAX_TEXT_ATTACHMENT_BYTES,exports.MemoryHintLedger=t.MemoryHintLedger,exports.MemoryRunStore=t.MemoryRunStore,exports.REFUSED_CREDENTIALS=t.REFUSED_CREDENTIALS,exports.REPORT_ARTIFACTS_KEY=t.REPORT_ARTIFACTS_KEY,exports.RESULT_BUDGET_TOKENS=t.RESULT_BUDGET_TOKENS,exports.RUNTIME_PROTOCOL_VERSION=t.RUNTIME_PROTOCOL_VERSION,exports.RUN_RECORD_VERSION=t.RUN_RECORD_VERSION,exports.SNAPSHOT_FORMAT_VERSION=t.SNAPSHOT_FORMAT_VERSION,exports.SUMMARIZE_MODEL_ALIAS=t.SUMMARIZE_MODEL_ALIAS,exports.SiteToolManager=t.SiteToolManager,exports.TemplateEnv=t.TemplateEnv,exports.TimeoutLlmClient=t.TimeoutLlmClient,exports.ToolDispatchException=t.ToolDispatchException,exports.XllmActionParser=t.XllmActionParser,exports.XllmInterrupter=t.XllmInterrupter,exports.XllmRun=t.XllmRun,exports.XllmTask=t.XllmTask,exports.XmlStepRenderer=t.XmlStepRenderer,exports.allowAllPolicy=t.allowAllPolicy,exports.applyHints=t.applyHints,exports.asToolResult=t.asToolResult,exports.assemblePrompt=t.assemblePrompt,exports.buildCmdManualSystemText=t.buildCmdManualSystemText,exports.buildRulesSystemText=t.buildRulesSystemText,exports.buildRuntimeProtocol=t.buildRuntimeProtocol,exports.buildRuntimeProtocolFor=t.buildRuntimeProtocolFor,exports.classifyError=t.classifyError,exports.clipToBudget=t.clipToBudget,exports.clipToDefaultBudget=t.clipToDefaultBudget,exports.compactionTargetTokens=t.compactionTargetTokens,exports.compress=t.compress,exports.compressHistory=t.compressHistory,exports.compressOptions=t.compressOptions,exports.computeToolsConfig=t.computeToolsConfig,exports.dedupText=t.dedupText,exports.envelopeObservation=t.envelopeObservation,exports.exportRun=t.exportRun,exports.extractResult=t.extractResult,exports.fitResultBudget=t.fitResultBudget,exports.followupGeneralHint=t.followupGeneralHint,exports.followupHint=t.followupHint,exports.fullText=t.fullText,exports.generateRunId=t.generateRunId,exports.importRun=t.importRun,exports.inCallWaitMs=t.inCallWaitMs,exports.inFlightCall=t.inFlightCall,exports.isIdempotent=t.isIdempotent,exports.isSummaryMessage=t.isSummaryMessage,exports.isTerminal=t.isTerminal,exports.materializeHistory=t.materializeHistory,exports.mergeConfigLayers=t.mergeConfigLayers,exports.noopWorklog=t.noopWorklog,exports.observationText=t.observationText,exports.parseLlmContextJson=t.parseLlmContextJson,exports.parseReply=t.parseReply,exports.parseSummaryMessage=t.parseSummaryMessage,exports.renderHintBlock=t.renderHintBlock,exports.renderStepHistory=t.renderStepHistory,exports.renderWithHints=t.renderWithHints,exports.reportArtifacts=t.reportArtifacts,exports.resolveToolSpecs=t.resolveToolSpecs,exports.resultView=t.resultView,exports.rewritableHistory=t.rewritableHistory,exports.runRequest=t.runRequest,exports.splitReportResult=t.splitReportResult,exports.stateFromRequest=t.stateFromRequest,exports.summaryMessage=t.summaryMessage,exports.summaryModel=t.summaryModel,exports.taskStateObservation=t.taskStateObservation,exports.toHost=t.toHost,exports.toolResultViewFromHost=t.toolResultViewFromHost,exports.unresolvedReason=t.unresolvedReason,exports.validateJson=t.validateJson,exports.waitUntilMs=t.waitUntilMs,exports.DIDObjectClient=o.DIDObjectClient,exports.DIDObjectError=o.DIDObjectError,exports.ACTION_RISKS=g,exports.INDEX_TRAIT_URI=M,exports.IndexedDbRunStore=class{constructor(e={}){this.options=e,this.persistent=!0,this.localLocks=new Set}open(){if(!this.db){const t=this.options.idb??globalThis.indexedDB;if(!t)return Promise.reject(e.XllmError.storage("IndexedDB is not available here"));const o=t.open(this.options.dbName??C,1);o.onupgradeneeded=()=>{const e=o.result;e.objectStoreNames.contains(D)||e.createObjectStore(D,{keyPath:"run_id"}),e.objectStoreNames.contains(U)||e.createObjectStore(U)},this.db=H(o)}return this.db}locks(){var e;if(null!==this.options.locks)return this.options.locks??(null==(e=globalThis.navigator)?void 0:e.locks)}runsDir(){}runDir(){}async createRun(){const o=await this.open();for(let e=0;e<8;e++){const e=t.generateRunId();if(!(await H(o.transaction(D).objectStore(D).get(e))))return e}throw e.XllmError.storage("cannot allocate a unique run id")}async writeRecord(e){const t=(await this.open()).transaction(D,"readwrite");t.objectStore(D).put(JSON.parse(JSON.stringify(e))),await P(t)}async readRecord(o){const r=await this.open(),n=await H(r.transaction(D).objectStore(D).get(o));if(!n)throw new e.XllmError({kind:"run_not_found",run_id:o,runs_dir:`indexeddb:${this.options.dbName??C}`});if(n.version!==t.RUN_RECORD_VERSION)throw e.XllmError.notResumable(o,"unsupported run record version");return n}async listRecords(){const e=await this.open();return await H(e.transaction(D).objectStore(D).getAll())}async putSnapshot(e,t){const o=(await this.open()).transaction(U,"readwrite"),r=o.objectStore(U),n=await H(r.getAllKeys(IDBKeyRange.bound([e,0],[e,Number.MAX_SAFE_INTEGER]))),s=n.length?Math.max(...n.map((e=>e[1])))+1:1;return r.put(JSON.parse(JSON.stringify(t)),[e,s]),await P(o),s}async getSnapshot(t,o){const r=await this.open(),n=await H(r.transaction(U).objectStore(U).get([t,o]));if(!n)throw new e.XllmError({kind:"corrupted_run",run_id:t,reason:`snapshot ${o} missing`});return n}async listSnapshots(e){const t=await this.open();return(await H(t.transaction(U).objectStore(U).getAllKeys(IDBKeyRange.bound([e,0],[e,Number.MAX_SAFE_INTEGER])))).map((e=>e[1])).sort(((e,t)=>e-t))}async lockRun(e){const t=`xllm-run:${e}`,o=this.locks();return o?new Promise(((e,r)=>{o.request(t,{ifAvailable:!0},(t=>t?new Promise((t=>e({release:()=>t()}))):(e(null),Promise.resolve()))).catch(r)})):this.localLocks.has(t)?null:(this.localLocks.add(t),{release:()=>{this.localLocks.delete(t)}})}async isRunLive(e){const t=`xllm-run:${e}`,o=this.locks();if(!o)return this.localLocks.has(t);return((await o.query()).held??[]).some((e=>e.name===t))}async removeRun(e){const t=(await this.open()).transaction([D,U],"readwrite");t.objectStore(D).delete(e),t.objectStore(U).delete(IDBKeyRange.bound([e,0],[e,Number.MAX_SAFE_INTEGER])),await P(t)}async importRun(e){const t=(await this.open()).transaction([D,U],"readwrite");t.objectStore(D).put(JSON.parse(JSON.stringify(e.record)));for(const[o,r]of e.snapshots)t.objectStore(U).put(JSON.parse(JSON.stringify(r)),[e.record.run_id,o]);await P(t)}},exports.MAX_RESULT_BYTES=_,exports.SITE_RUNTIME_KIND=r,exports.XCALL_USAGE=h,exports.XLLM_RUNS_DB=C,exports.createSiteRuntime=function(o){var i;const a=null==(i=o.scene)?void 0:i.trim();if(!a)throw e.XllmError.input("createSiteRuntime: `scene` is required");if(!o.origin)throw e.XllmError.input("createSiteRuntime: `origin` is required");const c=new Map;for(const[t,r]of Object.entries(o.tools??{})){if(!n.test(t))throw e.XllmError.tools(`site tool name \`${t}\` must match ${n}`);if(!r||"function"!=typeof r.call||!r.spec)throw e.XllmError.tools(`site tool \`${t}\` needs \`spec\` and \`call\``);c.set(t,r)}const l={...o.env??{}},u={runtime_id:`site:${a}`,kind:r,host:null,target:{origin:o.origin,scene:a},workdir:"/",capabilities:{tools:{},network:!0,os:"browser"}},p={kind:r,env:{}};return void 0!==o.task_wait_ms&&(p.task_wait_ms=o.task_wait_ms),{scene:a,tools:c,descriptor:()=>JSON.parse(JSON.stringify(u)),config:()=>JSON.parse(JSON.stringify(p)),async info(){let e="";try{e=Intl.DateTimeFormat().resolvedOptions().timeZone??""}catch{e=""}return{id:u.runtime_id,kind:r,os:"browser",arch:"",hostname:o.hostname,shell:"",cwd:"/",tools:[],current_time:(new Date).toISOString(),timezone:e,target:u.target,platform:"browser",shell_kind:"",baseline:""}},async open(o,r){const n=r.enabled??!1,i=r.tools2actions??!1;if("function_call"===o.loop_model&&(i||(r.actions??[]).length>0))throw e.XllmError.capability("actions / tools2actions need loop_model behavior");const l=(t,o)=>t.map((t=>{const r=c.get(t);if(!r)throw e.XllmError.capability(`${o}: \`${t}\` is not a tool of scene \`${a}\` (scene tools: ${[...c.keys()].join(", ")||"none"})`);return function(e,t,o){return{name:e,description:t.spec.description,args_schema:t.spec.args_schema,source:o}}(t,r,`name:${t}`)}));let u=[],d=[];const m=r.tools??[],f=r.actions??[];if(n){u=l(void 0===r.tools?[...c.keys()]:s(r.tools,"tools.tools"),"tools.tools"),d=l(s(r.actions,"tools.actions"),"tools.actions"),i&&(d=[...d,...u.filter((e=>!d.some((t=>t.name===e.name))))],u=[])}const g=new Map;for(const e of[...u,...d])g.set(e.name,c.get(e.name));return{tools:{enabled:n,filesystem_policy:r.filesystem_policy??"workspace",tools2actions:i,tool_sources:void 0===r.tools&&n?u.map((e=>({kind:"named",name:e.name}))):m,action_sources:f,native:u,actions:d,bash_tools:[],shell:t.shellSettings(r.shell,t.taskWaitMs(p)),exec_enabled:!1,sources:{...o.sources}},manager:new t.SiteToolManager(g,{tasks:o.tasks,taskWaitMs:o.task_wait_ms})}},async describeInterrupted(e,o){const r=c.get(o.name);if(null==r?void 0:r.describeInterrupted)try{return await r.describeInterrupted(o.args??{},{run_id:e.run_id,call_id:o.call_id,signal:(new AbortController).signal})}catch(n){return`${t.unresolvedReason(o.name)} (describing it failed: ${n instanceof Error?n.message:String(n)})`}return t.unresolvedReason(o.name)},env:e=>l[e]}},exports.didObjectResources=async function(t){const o=v(t.maxRisk??"read_only"),r={};for(const n of t.roots){const s=t.client,i=await s.profile(n),a=j(i),c={},l=e.isObject(i)&&e.isObject(i.actions)?i.actions:{};for(const[t,r]of Object.entries(l)){if(a&&("query"===t||"page"===t))continue;const i=L(r,"x-buckyos:risk");if(v(i)>o)continue;const l=e.isObject(r)?r.input:void 0;c[t]={description:L(r,"description"),risk:i,...null!=l?{input:l}:{},call:(e,o)=>s.invoke(n,t,o)}}const u=[L(i,"title"),L(i,"description")].filter(Boolean).join(" — ")||n;r[n]={description:a?`${u} (a collection: read it with a query, ?cursor=… for the next page)`:u,actions:c,async read(t){if(a&&[...t.query.keys()].length>0){const e=t.query.get("cursor"),o=t.query.get("page_size");if(e)return s.invoke(n,"page",{cursor:e,...o?{page_size:Number(o)}:{}});const r={};for(const[n,s]of t.query)"page_size"!==n&&(r[n]=s);return s.invoke(n,"query",{query:r,...o?{page_size:Number(o)}:{}})}const o=await s.card(n),r=e.isObject(i)&&e.isObject(i.properties)?Object.keys(i.properties).filter((e=>"index_schema"!==e)):[],c=e.isObject(i)&&Array.isArray(i["x-buckyos:summary_props"])?i["x-buckyos:summary_props"].filter((e=>"string"==typeof e)):r,l={};for(const e of c)l[e]=await s.readProperty(n,e);return k(n,{id:String(o.id),alsoKnownAs:o.alsoKnownAs},i,l)}}}return r},exports.normalizeUri=T,exports.pageText=O,exports.renderObjectDocument=k,exports.siteTools=function(e){const o=Object.entries(e.resources??{}).map((([e,t])=>function(e,t){const o=e.indexOf("://");if(o>=0){const r=e.slice(o+3),n=r.indexOf("/"),s=n<0?r:r.slice(0,n),i=n<0?"":r.slice(n+1);return{raw:e,origin:`${e.slice(0,o).toLowerCase()}://${s.toLowerCase()}`,segments:i?i.split("/"):[],decl:t}}const r=e.replace(/^\/+/,"").replace(/\/+$/,"");return{raw:e,segments:r?r.split("/"):[],decl:t}}(e,t))),r=new Set(o.map((e=>e.origin)).filter((e=>void 0!==e))),n=new Map(Object.entries(e.commands??{}));if(n.has("xcall"))throw new Error("siteTools: `xcall` is built in; declare actions on resources instead");const s=(e,t)=>{const n=T(e,r);for(const r of o){const e=S(r,n.origin,n.segments);if(e)return{uri:n.text,pattern:r.raw,params:e,query:n.query,ctx:t,decl:r.decl}}y(`uri \`${e}\` is not a resource of this page; read uri="/" lists them`)},g=async(e,o)=>{var r;const g=(()=>{try{return m(e)}catch(t){y(`${t instanceof Error?t.message:String(t)}; exec runs one command, it is not a shell`)}})(),T="available commands: xcall"+(n.size?`, ${[...n.keys()].join(", ")}`:""),S=e.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g,"");x.test(S)&&y(`exec runs exactly one command and is not a shell: pipes, redirects, \`;\`, \`&\`, backquotes and \`$\` are not supported (quote them to pass them as text). ${T}`);const[w,...O]=g;if(w||y(`empty command; ${T}`),"xcall"===w){if(O.includes("--help")||O.includes("-h"))return`usage: ${h}\nThe actions of each resource are listed by read uri="/".`;const{object:e,action:n,params:i}=I(O),a=s(e,o),c=null==(r=a.decl.actions)?void 0:r[n];if(!c){const e=Object.keys(a.decl.actions??{});y(`resource \`${a.pattern}\` has no action \`${n}\` (actions: ${e.length?e.join(", "):"none"})`)}if(void 0!==c.input){const e=t.validateJson(c.input,i);e&&y(`invalid params for ${n}: ${e}`)}const{decl:l,...u}=a,p=await c.call(u,i);return`[risk: ${c.risk}]\n${b(E(p)||"ok",_).text}`}const A=n.get(w);let R;A||y(`unknown command \`${w}\`; exec runs one command, it is not a shell. ${T}`);try{const e=function(e,t,o){const r={},n=e.positionals??[],s=new Map((e.options??[]).map((e=>[e.name,e])));let m=0,f=!1;for(let g=0;g<t.length;){const e=t[g];if("--help"===e||"-h"===e){f=!0,g+=1;continue}if("--"===e){for(const e of t.slice(g+1))m=d(r,n,m,e);break}if(!e.startsWith("--")){m=d(r,n,m,e),g+=1;continue}const h=l(e),_=null==o?void 0:o(h,t,g);if(void 0!==_){g+=_;continue}const x=s.get(h.name);if(!x)throw new i("UNKNOWN_OPTION",`unknown option: --${h.name}`);const y=c(x);if(a(r,y))throw new i("DUPLICATE_ARGUMENT",`argument provided more than once: ${y}`);if("boolean"===x.type){if(void 0!==h.inlineValue)throw new i("INVALID_ARGUMENT",`--${h.name} does not accept a value`);r[y]=!0,g+=1;continue}const{value:T,consumed:S}=u(t,g,h);r[y]=p(x.type,T,h.name),g+=S}return{input:r,help:f,positionalCount:m}}({positionals:A.positionals,options:A.options},O);if(e.help)return $(w,A);for(let t=e.positionalCount;t<(A.positionals??[]).length;t++)if(!1!==(A.positionals??[])[t].required)throw new i("MISSING_ARGUMENT",`missing positional argument: ${(A.positionals??[])[t].name}`);for(const t of A.options??[]){const o=t.property??t.name.split("-").join("_");if(t.required&&!(o in e.input))throw new i("MISSING_ARGUMENT",`--${t.name} is required`)}R=e.input,A.inputSchema&&f(R,A.inputSchema,"input")}catch(N){throw N instanceof i&&y(`${w}: ${N.message}\n\n${$(w,A)}`),N}return b(E(await A.call(R,o))||"ok",_).text};return{read:{spec:{description:'Read a resource of this page by URI (GET). Start with uri "/": it lists the resources, their actions (with risk) and the commands. A collection\'s read is its list; filter and page with a query (notes?tag=x). Text comes in pages of lines: offset is the first line (1-based), limit the number of lines.',args_schema:N({uri:{type:"string",description:'Resource URI, e.g. "/" or "notes/1"'},offset:{type:"integer",description:"First line, 1-based"},limit:{type:"integer",description:"Number of lines"}},["uri"])},idempotent:!0,async call(e,t){const r=String(e.uri),i="number"==typeof e.offset?e.offset:void 0,a="number"==typeof e.limit?e.limit:void 0;if("/"===r.trim()||""===r.trim())return O((()=>{const e=['Resources (read uri="<resource>"; {name} is one path segment):'];for(const t of o){const o=["read","write","edit"].filter((e=>"edit"===e?!!(t.decl.edit||t.decl.read&&t.decl.write):!!t.decl[e]));e.push(`- ${t.raw} — ${t.decl.description} [${o.join(", ")||"no methods"}]`);for(const[r,n]of Object.entries(t.decl.actions??{}))e.push(` action ${r} (risk: ${n.risk}) — ${n.description}`)}0===o.length&&e.push("(none)"),e.push("",'Commands (exec "<command> --help" for usage):'),e.push(`- xcall — call an action of a resource: ${h}`);for(const[t,o]of n)e.push(`- ${t} — ${o.summary}`);return e.join("\n")})(),i,a);return O((await(async e=>{e.decl.read||y(`resource \`${e.pattern}\` cannot be read`);const{decl:t,...o}=e;return w(await e.decl.read(o))})(s(r,t))).text,i,a)}},write:{spec:{description:'Write a resource\'s content (PUT). mode: "write" (default) replaces it, "new" only creates it and fails if it exists, "append" adds to its end. Use edit to change part of it.',args_schema:N({uri:{type:"string",description:"Resource URI"},content:{type:"string",description:"The content"},mode:{type:"string",enum:["write","new","append"],description:"write | new | append"}},["uri","content"])},async call(e,t){const o=s(String(e.uri),t);o.decl.write||y(`resource \`${o.pattern}\` is read-only`);const{decl:r,...n}=o,i="string"==typeof e.mode?e.mode:"write";return E(await r.write(n,{content:String(e.content),mode:i}))||"written"}},edit:{spec:{description:"Change part of a resource (PATCH): old_string must occur exactly once in its current content and is replaced by new_string.",args_schema:N({uri:{type:"string",description:"Resource URI"},old_string:{type:"string",description:"Text to replace; must occur exactly once"},new_string:{type:"string",description:"Replacement text"}},["uri","old_string","new_string"])},async call(e,t){const o=s(String(e.uri),t),r={old_string:String(e.old_string),new_string:String(e.new_string)},{decl:n,...i}=o;if(n.edit)return E(await n.edit(i,r))||"edited";n.read&&n.write||y(`resource \`${o.pattern}\` cannot be edited`),r.old_string||y("old_string is empty");const a=w(await n.read(i)),c=a.text.split(r.old_string).length-1;0===c&&y("old_string was not found in the current content; read it again"),c>1&&y(`old_string occurs ${c} times; give more context so it occurs exactly once`);const l={content:a.text.replace(r.old_string,(()=>r.new_string)),mode:"write"};return void 0!==a.version&&(l.ifVersion=a.version),E(await n.write(i,l))||"edited"}},exec:{spec:{description:`Run one command (not a shell: no pipes, redirects, ;, &, backquotes or $). Built in: ${h} — calls an action listed by read uri="/". The page's commands are listed there too; "<command> --help" shows a command's usage.`,args_schema:N({command:{type:"string",description:"One command line"}},["command"])},idempotent:e=>function(e,t,o,r){var n,s,i;let a;try{a=m(e)}catch{return!1}const[c,...l]=a;if("xcall"===c)try{const{object:e,action:r}=I(l),i=T(e,o),a=t.find((e=>S(e,i.origin,i.segments))),c=null==(s=null==(n=null==a?void 0:a.decl.actions)?void 0:n[r])?void 0:s.risk;return"read_only"===c||"idempotent_write"===c}catch{return!1}const u=c?r.get(c):void 0;return"read"===(null==(i=null==u?void 0:u.access)?void 0:i.level)}(String(e.command??""),o,r,n),call:(e,t)=>g(String(e.command),t)}}};
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./aicc-342f2659.js"),t=require("./site_manager-ca22ffbd.js"),o=require("./did_object_client-27835522.js");require("./krpc_client-26c2dc8b.js"),require("./object_url-88047ee2.js"),require("./ndn_types-5b138882.js");const r="site",n=/^[A-Za-z0-9_-]{1,64}$/;function s(o,r){return(o??[]).map((o=>{if("named"!==o.kind)throw e.XllmError.capability(`${r}: \`${t.describeToolSource(o)}\` is not available in a site runtime; only the page's tools can be named`);return o.name}))}class i extends Error{constructor(e,t){super(t),this.name="CommandArgsError",this.code=e}}function a(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function c(e){return e.property??e.name.split("-").join("_")}function l(e){const t=e.slice(2),o=t.indexOf("=");return o<0?{name:t}:{name:t.slice(0,o),inlineValue:t.slice(o+1)}}function u(e,t,o){if(void 0!==o.inlineValue){if(!o.inlineValue)throw new i("MISSING_ARGUMENT",`--${o.name} requires a value`);return{value:o.inlineValue,consumed:1}}const r=e[t+1];if(void 0===r||r.startsWith("--"))throw new i("MISSING_ARGUMENT",`--${o.name} requires a value`);return{value:r,consumed:2}}function p(e,t,o){if("string"===e)return t;const r=Number(t);if(!Number.isFinite(r)||"integer"===e&&!Number.isInteger(r))throw new i("INVALID_ARGUMENT",`--${o} requires a ${e}`);return r}function d(e,t,o,r){const n=t[o];if(!n)throw new i("TOO_MANY_ARGUMENTS",`unexpected positional argument: ${r}`);return e[n.name]=r,o+1}function m(e){const t=[];let o="",r=null,n=!1,s=!1;for(const i of e)n?(o+=i,n=!1,s=!0):"\\"!==i||"single"===r?"single"!==r?"double"!==r?"'"!==i?'"'!==i?/\s/.test(i)?s&&(t.push(o),o="",s=!1):(o+=i,s=!0):(r="double",s=!0):(r="single",s=!0):'"'===i?r=null:o+=i:"'"===i?r=null:o+=i:(n=!0,s=!0);if(n)throw new i("INVALID_COMMAND_LINE","unfinished escape sequence");if(r)throw new i("INVALID_COMMAND_LINE",`unterminated ${r} quote`);return s&&t.push(o),t}function f(e,t,o){var r;if(t.enum&&!t.enum.some((t=>Object.is(t,e))))throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be one of ${t.enum.join(", ")}`);if("object"!==t.type)if("array"!==t.type)if("string"!==t.type){if("boolean"===t.type&&"boolean"!=typeof e)throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be a boolean`);if("integer"===t.type&&(!Number.isInteger(e)||"number"!=typeof e))throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be an integer`);if("number"===t.type&&"number"!=typeof e)throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be a number`)}else{if("string"!=typeof e)throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be a string`);if(void 0!==t.minLength&&e.length<t.minLength)throw new i("SCHEMA_VALIDATION_FAILED",`${o} is too short`)}else{if(!Array.isArray(e))throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be an array`);const r=t.items;r&&e.forEach(((e,t)=>f(e,r,`${o}[${t}]`)))}else{if(!e||"object"!=typeof e||Array.isArray(e))throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be an object`);const n=e;for(const e of t.required??[])if(!a(n,e))throw new i("SCHEMA_VALIDATION_FAILED",`${o}.${e} is required`);if(!1===t.additionalProperties)for(const e of Object.keys(n))if(!a(t.properties??{},e))throw new i("SCHEMA_VALIDATION_FAILED",`${o}.${e} is not allowed`);for(const[e,s]of Object.entries(n)){const n=null==(r=t.properties)?void 0:r[e];n&&f(s,n,`${o}.${e}`)}}}const g=["read_only","idempotent_write","write","destructive","admin"],h="xcall <object> <action> [--params <json>] [key=value ...] [--key=value ...]",_=65536,x=/[|;&><`$]/;function y(e){throw new Error(e)}function T(e,t){const o=e.trim();o||y("uri is empty");const r=/^[A-Za-z][A-Za-z0-9+.-]*:/.test(o);let n,s;try{n=r?new URL(o):new URL(o.replace(/^\/+/,""),"site://page/")}catch{y(`invalid uri \`${o}\``)}r?(s=`${n.protocol.slice(0,-1).toLowerCase()}://${n.host.toLowerCase()}`,t.has(s)||y(`uri \`${o}\` is not a resource of this page (absolute URIs are limited to the declared ones)`)):"site:"===n.protocol&&"page"===n.host||y(`uri \`${o}\` is not a resource of this page`);const i=[];for(const c of n.pathname.split("/")){if(""===c)continue;let e;try{e=decodeURIComponent(c)}catch{y(`invalid uri \`${o}\``)}(".."===e||"."===e||e.includes("/")||e.includes("\\"))&&y(`uri \`${o}\` is not a resource of this page`),i.push(e)}const a=(s?`${s}/`:"")+i.join("/")+(n.search||"");return{origin:s,segments:i,query:n.searchParams,text:a}}function S(e,t,o){if(e.origin!==t||e.segments.length!==o.length)return;const r={};for(let n=0;n<o.length;n++){const t=e.segments[n];if(t.startsWith("{")&&t.endsWith("}"))r[t.slice(1,-1)]=o[n];else if(t!==o[n])return}return r}function E(e){if(null==e)return"";if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function w(t){if(e.isObject(t)&&"content"in t&&Object.keys(t).every((e=>"content"===e||"version"===e))){const e=t.version;return{text:E(t.content),version:"string"==typeof e?e:void 0===e?void 0:String(e)}}return{text:E(t)}}function b(e,o){if(t.utf8Length(e)<=o)return{text:e,clipped:!1};let r="",n=0;for(const s of e){const e=t.utf8Length(s);if(n+e>o)break;r+=s,n+=e}return{text:r,clipped:!0}}function O(e,o=1,r){const n=e.split("\n"),s=Math.max(1,Math.floor(o));if(s>n.length&&(1!==s||1!==n.length))return`[offset ${s} is past the end: ${n.length} lines]`;const i=void 0===r?n.length:Math.max(1,Math.floor(r)),a=[];let c=0,l=s-1;for(;l<n.length&&a.length<i;l++){const e=t.utf8Length(n[l])+1;if(a.length>0&&c+e>_)break;a.push(n[l]),c+=e}let u=a.join("\n");return 1===a.length&&t.utf8Length(u)>_&&(u=b(u,_).text+" …"),l<n.length&&(u+=`\n[lines ${s}–${l} of ${n.length}; read on with offset=${l+1}]`),u}function A(e){const t=e.trim();if("true"===t)return!0;if("false"===t)return!1;if("null"===t)return null;if(/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(t))return Number(t);if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t)}catch{return t}return t}const R=["config","route-config","session-id","session_id","idempotency-key","idempotency_key","confirm-token","confirm_token","trace-id","trace_id"];function I(t){let o,r,n={};const s={},i=[],a=(e,t)=>{try{return JSON.parse(e)}catch(o){y(`invalid \`${t}\` JSON value \`${e}\`: ${o instanceof Error?o.message:String(o)}\nusage: ${h}`)}},c=e=>y(`unsupported flag \`${e}\` (routing and confirmation are the page's)\nusage: ${h}`);for(let e=0;e<t.length;e++){const l=t[e];if("--params"===l){const o=t[++e];void 0===o&&y(`missing value for --params\nusage: ${h}`),n=a(o,"--params")}else if(l.startsWith("--")){const e=l.indexOf("=");e<0&&c(l);const t=l.slice(2,e),o=l.slice(e+1);"params"===t?n=a(o,"--params"):!t.trim()||t.startsWith("-")||R.includes(t)?c(l):s[t]=A(o)}else if(l.includes("=")){const e=l.indexOf("="),t=l.slice(0,e),i=l.slice(e+1);"object"===t?o=i:"action"===t?r=i:"params"===t?n=a(i,"params"):R.includes(t)?c(l):s[t]=A(i)}else i.push(l)}return o=o??i[0],r=r??i[1],void 0!==i[2]&&(n=a(i[2],"params")),i.length>3&&y(`unexpected positional argument \`${i[3]}\`\nusage: ${h}`),Object.keys(s).length&&(e.isObject(n)||y(`key=value params require object params\nusage: ${h}`),n={...n,...s}),o&&r||y(`xcall needs an object and an action\nusage: ${h}`),e.isObject(n)||y(`params must be a JSON object\nusage: ${h}`),{object:o,action:r,params:n}}function $(e,t){var o;const r=[`${e} — ${t.summary}`];t.description&&r.push("",t.description);const n=(t.positionals??[]).map((e=>!1===e.required?`[${e.name}]`:`<${e.name}>`)).join(" ");r.push("",`usage: ${e}${n?` ${n}`:""}${(t.options??[]).length?" [options]":""}`);for(const s of t.positionals??[])r.push(` ${s.name} ${s.description}`);(t.options??[]).length&&r.push("options:");for(const s of t.options??[])r.push(` --${s.name}${"boolean"===s.type?"":` <${s.type}>`}${s.required?" (required)":""} ${s.description}${s.enum?` (${s.enum.join(" | ")})`:""}`);if(null==(o=t.examples)?void 0:o.length){r.push("examples:");for(const e of t.examples)r.push(` ${e}`)}return r.join("\n")}const N=(e,t)=>({type:"object",properties:e,required:t});const M="https://buckyos.org/traits/index@1";function L(t,o){return e.isObject(t)&&"string"==typeof t[o]?t[o]:""}function v(e){const t=g.indexOf(e);return t<0?g.length:t}function k(t,o,r,n){const s=[`Object: ${t}`,`Object DID: ${o.id}`],i=(o.alsoKnownAs??[]).filter((e=>e!==t));i.length&&s.push(`Also known as: ${i.join(", ")}`);for(const[e,c]of[["Title","title"],["Description","description"]]){const t=L(r,c);t&&s.push(`${e}: ${t}`)}for(const[c,l]of[["Properties","properties"],["Actions","actions"],["Events","events"]]){const t=e.isObject(r)?r[l]:void 0;if(e.isObject(t)&&0!==Object.keys(t).length){s.push(`${c}:`);for(const e of Object.keys(t).sort()){const o=t[e];let r=`- ${e}`;const n=L(o,"description");n&&(r+=`: ${n}`);const i=L(o,"x-buckyos:risk");i&&(r+=` (risk: ${i})`),s.push(r)}}}const a=Object.keys(n);if(a.length){s.push("Summary:");for(const e of a)s.push(`- ${e}:`,JSON.stringify(n[e],null,2))}return s.join("\n")}function j(t){const o=e.isObject(t)?t["x-buckyos:traits"]:void 0;return Array.isArray(o)&&o.includes(M)}const C="xllm-runs",D="records",U="snapshots";function H(e){return new Promise(((t,o)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>o(e.error)}))}function P(e){return new Promise(((t,o)=>{e.oncomplete=()=>t(),e.onerror=()=>o(e.error),e.onabort=()=>o(e.error??new Error("transaction aborted"))}))}exports.AiccLlmClient=e.AiccLlmClient,exports.LLMComputeException=e.LLMComputeException,exports.XllmError=e.XllmError,exports.aiccProviderFailure=e.aiccProviderFailure,exports.anyJsonObjectSchema=e.anyJsonObjectSchema,exports.asComputeError=e.asComputeError,exports.charCount=e.charCount,exports.computeErrorMessage=e.computeErrorMessage,exports.errorSource=e.errorSource,exports.infraRetrySafe=e.infraRetrySafe,exports.llmCorrectable=e.llmCorrectable,exports.providerError=e.providerError,exports.providerErrorFromRpc=e.providerErrorFromRpc,exports.rustTrim=e.rustTrim,exports.rustTrimEnd=e.rustTrimEnd,exports.rustTrimStart=e.rustTrimStart,exports.serdeJson=e.serdeJson,exports.AGENT_TOOL_PROTOCOL_VERSION=t.AGENT_TOOL_PROTOCOL_VERSION,exports.ByteHeuristicTokenizer=t.ByteHeuristicTokenizer,exports.DEFAULT_CONTEXT_YIELD_RATIO=t.DEFAULT_CONTEXT_YIELD_RATIO,exports.DEFAULT_LLM_TIMEOUT_SECS=t.DEFAULT_LLM_TIMEOUT_SECS,exports.DEFAULT_MAX_CONSECUTIVE_ERRORS=t.DEFAULT_MAX_CONSECUTIVE_ERRORS,exports.DEFAULT_MAX_TOOL_ITERATIONS=t.DEFAULT_MAX_TOOL_ITERATIONS,exports.DEFAULT_TASK_WAIT_MS=t.DEFAULT_TASK_WAIT_MS,exports.DEFAULT_TIMEOUT_SECS=t.DEFAULT_TIMEOUT_SECS,exports.HINT_NS_DEDUP=t.HINT_NS_DEDUP,exports.HINT_NS_ONCE=t.HINT_NS_ONCE,exports.HOST_PROMPT_SECTIONS_ALL=t.HOST_PROMPT_SECTIONS_ALL,exports.HOST_PROMPT_SECTIONS_NONE=t.HOST_PROMPT_SECTIONS_NONE,exports.LLMContext=t.LLMContext,exports.LLMContextInterruptHandle=t.LLMContextInterruptHandle,exports.LlmSummarizeCompressor=t.LlmSummarizeCompressor,exports.MAX_IMAGE_ATTACHMENT_BYTES=t.MAX_IMAGE_ATTACHMENT_BYTES,exports.MAX_INJECTIONS_PER_BOUNDARY=t.MAX_INJECTIONS_PER_BOUNDARY,exports.MAX_IN_TOOL_WAIT_MS=t.MAX_IN_TOOL_WAIT_MS,exports.MAX_TEXT_ATTACHMENT_BYTES=t.MAX_TEXT_ATTACHMENT_BYTES,exports.MemoryHintLedger=t.MemoryHintLedger,exports.MemoryRunStore=t.MemoryRunStore,exports.REFUSED_CREDENTIALS=t.REFUSED_CREDENTIALS,exports.REPORT_ARTIFACTS_KEY=t.REPORT_ARTIFACTS_KEY,exports.RESULT_BUDGET_TOKENS=t.RESULT_BUDGET_TOKENS,exports.RUNTIME_PROTOCOL_VERSION=t.RUNTIME_PROTOCOL_VERSION,exports.RUN_RECORD_VERSION=t.RUN_RECORD_VERSION,exports.SNAPSHOT_FORMAT_VERSION=t.SNAPSHOT_FORMAT_VERSION,exports.SUMMARIZE_MODEL_ALIAS=t.SUMMARIZE_MODEL_ALIAS,exports.SiteToolManager=t.SiteToolManager,exports.TemplateEnv=t.TemplateEnv,exports.TimeoutLlmClient=t.TimeoutLlmClient,exports.ToolDispatchException=t.ToolDispatchException,exports.XllmActionParser=t.XllmActionParser,exports.XllmInterrupter=t.XllmInterrupter,exports.XllmRun=t.XllmRun,exports.XllmTask=t.XllmTask,exports.XmlStepRenderer=t.XmlStepRenderer,exports.allowAllPolicy=t.allowAllPolicy,exports.applyHints=t.applyHints,exports.asToolResult=t.asToolResult,exports.assemblePrompt=t.assemblePrompt,exports.buildCmdManualSystemText=t.buildCmdManualSystemText,exports.buildRulesSystemText=t.buildRulesSystemText,exports.buildRuntimeProtocol=t.buildRuntimeProtocol,exports.buildRuntimeProtocolFor=t.buildRuntimeProtocolFor,exports.classifyError=t.classifyError,exports.clipToBudget=t.clipToBudget,exports.clipToDefaultBudget=t.clipToDefaultBudget,exports.compactionTargetTokens=t.compactionTargetTokens,exports.compress=t.compress,exports.compressHistory=t.compressHistory,exports.compressOptions=t.compressOptions,exports.computeToolsConfig=t.computeToolsConfig,exports.dedupText=t.dedupText,exports.envelopeObservation=t.envelopeObservation,exports.exportRun=t.exportRun,exports.extractResult=t.extractResult,exports.fitResultBudget=t.fitResultBudget,exports.followupGeneralHint=t.followupGeneralHint,exports.followupHint=t.followupHint,exports.fullText=t.fullText,exports.generateRunId=t.generateRunId,exports.importRun=t.importRun,exports.inCallWaitMs=t.inCallWaitMs,exports.inFlightCall=t.inFlightCall,exports.isIdempotent=t.isIdempotent,exports.isSummaryMessage=t.isSummaryMessage,exports.isTerminal=t.isTerminal,exports.materializeHistory=t.materializeHistory,exports.mergeConfigLayers=t.mergeConfigLayers,exports.noopWorklog=t.noopWorklog,exports.observationText=t.observationText,exports.parseLlmContextJson=t.parseLlmContextJson,exports.parseReply=t.parseReply,exports.parseSummaryMessage=t.parseSummaryMessage,exports.renderHintBlock=t.renderHintBlock,exports.renderStepHistory=t.renderStepHistory,exports.renderWithHints=t.renderWithHints,exports.reportArtifacts=t.reportArtifacts,exports.resolveToolSpecs=t.resolveToolSpecs,exports.resultView=t.resultView,exports.rewritableHistory=t.rewritableHistory,exports.runRequest=t.runRequest,exports.splitReportResult=t.splitReportResult,exports.stateFromRequest=t.stateFromRequest,exports.summaryMessage=t.summaryMessage,exports.summaryModel=t.summaryModel,exports.taskStateObservation=t.taskStateObservation,exports.toHost=t.toHost,exports.toolResultViewFromHost=t.toolResultViewFromHost,exports.unresolvedReason=t.unresolvedReason,exports.validateJson=t.validateJson,exports.waitUntilMs=t.waitUntilMs,exports.DIDObjectClient=o.DIDObjectClient,exports.DIDObjectError=o.DIDObjectError,exports.ACTION_RISKS=g,exports.INDEX_TRAIT_URI=M,exports.IndexedDbRunStore=class{constructor(e={}){this.options=e,this.persistent=!0,this.localLocks=new Set}open(){if(!this.db){const t=this.options.idb??globalThis.indexedDB;if(!t)return Promise.reject(e.XllmError.storage("IndexedDB is not available here"));const o=t.open(this.options.dbName??C,1);o.onupgradeneeded=()=>{const e=o.result;e.objectStoreNames.contains(D)||e.createObjectStore(D,{keyPath:"run_id"}),e.objectStoreNames.contains(U)||e.createObjectStore(U)},this.db=H(o)}return this.db}locks(){var e;if(null!==this.options.locks)return this.options.locks??(null==(e=globalThis.navigator)?void 0:e.locks)}runsDir(){}runDir(){}async createRun(){const o=await this.open();for(let e=0;e<8;e++){const e=t.generateRunId();if(!(await H(o.transaction(D).objectStore(D).get(e))))return e}throw e.XllmError.storage("cannot allocate a unique run id")}async writeRecord(e){const t=(await this.open()).transaction(D,"readwrite");t.objectStore(D).put(JSON.parse(JSON.stringify(e))),await P(t)}async readRecord(o){const r=await this.open(),n=await H(r.transaction(D).objectStore(D).get(o));if(!n)throw new e.XllmError({kind:"run_not_found",run_id:o,runs_dir:`indexeddb:${this.options.dbName??C}`});if(n.version!==t.RUN_RECORD_VERSION)throw e.XllmError.notResumable(o,"unsupported run record version");return n}async listRecords(){const e=await this.open();return await H(e.transaction(D).objectStore(D).getAll())}async putSnapshot(e,t){const o=(await this.open()).transaction(U,"readwrite"),r=o.objectStore(U),n=await H(r.getAllKeys(IDBKeyRange.bound([e,0],[e,Number.MAX_SAFE_INTEGER]))),s=n.length?Math.max(...n.map((e=>e[1])))+1:1;return r.put(JSON.parse(JSON.stringify(t)),[e,s]),await P(o),s}async getSnapshot(t,o){const r=await this.open(),n=await H(r.transaction(U).objectStore(U).get([t,o]));if(!n)throw new e.XllmError({kind:"corrupted_run",run_id:t,reason:`snapshot ${o} missing`});return n}async listSnapshots(e){const t=await this.open();return(await H(t.transaction(U).objectStore(U).getAllKeys(IDBKeyRange.bound([e,0],[e,Number.MAX_SAFE_INTEGER])))).map((e=>e[1])).sort(((e,t)=>e-t))}async lockRun(e){const t=`xllm-run:${e}`,o=this.locks();return o?new Promise(((e,r)=>{o.request(t,{ifAvailable:!0},(t=>t?new Promise((t=>e({release:()=>t()}))):(e(null),Promise.resolve()))).catch(r)})):this.localLocks.has(t)?null:(this.localLocks.add(t),{release:()=>{this.localLocks.delete(t)}})}async isRunLive(e){const t=`xllm-run:${e}`,o=this.locks();if(!o)return this.localLocks.has(t);return((await o.query()).held??[]).some((e=>e.name===t))}async removeRun(e){const t=(await this.open()).transaction([D,U],"readwrite");t.objectStore(D).delete(e),t.objectStore(U).delete(IDBKeyRange.bound([e,0],[e,Number.MAX_SAFE_INTEGER])),await P(t)}async importRun(e){const t=(await this.open()).transaction([D,U],"readwrite");t.objectStore(D).put(JSON.parse(JSON.stringify(e.record)));for(const[o,r]of e.snapshots)t.objectStore(U).put(JSON.parse(JSON.stringify(r)),[e.record.run_id,o]);await P(t)}},exports.MAX_RESULT_BYTES=_,exports.SITE_RUNTIME_KIND=r,exports.XCALL_USAGE=h,exports.XLLM_RUNS_DB=C,exports.createSiteRuntime=function(o){var i;const a=null==(i=o.scene)?void 0:i.trim();if(!a)throw e.XllmError.input("createSiteRuntime: `scene` is required");if(!o.origin)throw e.XllmError.input("createSiteRuntime: `origin` is required");const c=new Map;for(const[t,r]of Object.entries(o.tools??{})){if(!n.test(t))throw e.XllmError.tools(`site tool name \`${t}\` must match ${n}`);if(!r||"function"!=typeof r.call||!r.spec)throw e.XllmError.tools(`site tool \`${t}\` needs \`spec\` and \`call\``);c.set(t,r)}const l={...o.env??{}},u={runtime_id:`site:${a}`,kind:r,host:null,target:{origin:o.origin,scene:a},workdir:"/",capabilities:{tools:{},network:!0,os:"browser"}},p={kind:r,env:{}};return void 0!==o.task_wait_ms&&(p.task_wait_ms=o.task_wait_ms),{scene:a,tools:c,descriptor:()=>JSON.parse(JSON.stringify(u)),config:()=>JSON.parse(JSON.stringify(p)),async info(){let e="";try{e=Intl.DateTimeFormat().resolvedOptions().timeZone??""}catch{e=""}return{id:u.runtime_id,kind:r,os:"browser",arch:"",hostname:o.hostname,shell:"",cwd:"/",tools:[],current_time:(new Date).toISOString(),timezone:e,target:u.target,platform:"browser",shell_kind:"",baseline:""}},async open(o,r){const n=r.enabled??!1,i=r.tools2actions??!1;if("function_call"===o.loop_model&&(i||(r.actions??[]).length>0))throw e.XllmError.capability("actions / tools2actions need loop_model behavior");const l=(t,o)=>t.map((t=>{const r=c.get(t);if(!r)throw e.XllmError.capability(`${o}: \`${t}\` is not a tool of scene \`${a}\` (scene tools: ${[...c.keys()].join(", ")||"none"})`);return function(e,t,o){return{name:e,description:t.spec.description,args_schema:t.spec.args_schema,source:o}}(t,r,`name:${t}`)}));let u=[],d=[];const m=r.tools??[],f=r.actions??[];if(n){u=l(void 0===r.tools?[...c.keys()]:s(r.tools,"tools.tools"),"tools.tools"),d=l(s(r.actions,"tools.actions"),"tools.actions"),i&&(d=[...d,...u.filter((e=>!d.some((t=>t.name===e.name))))],u=[])}const g=new Map;for(const e of[...u,...d])g.set(e.name,c.get(e.name));return{tools:{enabled:n,filesystem_policy:r.filesystem_policy??"workspace",tools2actions:i,tool_sources:void 0===r.tools&&n?u.map((e=>({kind:"named",name:e.name}))):m,action_sources:f,native:u,actions:d,bash_tools:[],shell:t.shellSettings(r.shell,t.taskWaitMs(p)),exec_enabled:!1,sources:{...o.sources}},manager:new t.SiteToolManager(g,{tasks:o.tasks,taskWaitMs:o.task_wait_ms})}},async describeInterrupted(e,o){const r=c.get(o.name);if(null==r?void 0:r.describeInterrupted)try{return await r.describeInterrupted(o.args??{},{run_id:e.run_id,call_id:o.call_id,signal:(new AbortController).signal})}catch(n){return`${t.unresolvedReason(o.name)} (describing it failed: ${n instanceof Error?n.message:String(n)})`}return t.unresolvedReason(o.name)},env:e=>l[e]}},exports.didObjectResources=async function(t){const o=v(t.maxRisk??"read_only"),r={};for(const n of t.roots){const s=t.client,i=await s.profile(n),a=j(i),c={},l=e.isObject(i)&&e.isObject(i.actions)?i.actions:{};for(const[t,r]of Object.entries(l)){if(a&&("query"===t||"page"===t))continue;const i=L(r,"x-buckyos:risk");if(v(i)>o)continue;const l=e.isObject(r)?r.input:void 0;c[t]={description:L(r,"description"),risk:i,...null!=l?{input:l}:{},call:(e,o)=>s.invoke(n,t,o)}}const u=[L(i,"title"),L(i,"description")].filter(Boolean).join(" — ")||n;r[n]={description:a?`${u} (a collection: read it with a query, ?cursor=… for the next page)`:u,actions:c,async read(t){if(a&&[...t.query.keys()].length>0){const e=t.query.get("cursor"),o=t.query.get("page_size");if(e)return s.invoke(n,"page",{cursor:e,...o?{page_size:Number(o)}:{}});const r={};for(const[n,s]of t.query)"page_size"!==n&&(r[n]=s);return s.invoke(n,"query",{query:r,...o?{page_size:Number(o)}:{}})}const o=await s.card(n),r=e.isObject(i)&&e.isObject(i.properties)?Object.keys(i.properties).filter((e=>"index_schema"!==e)):[],c=e.isObject(i)&&Array.isArray(i["x-buckyos:summary_props"])?i["x-buckyos:summary_props"].filter((e=>"string"==typeof e)):r,l={};for(const e of c)l[e]=await s.readProperty(n,e);return k(n,{id:String(o.id),alsoKnownAs:o.alsoKnownAs},i,l)}}}return r},exports.normalizeUri=T,exports.pageText=O,exports.renderObjectDocument=k,exports.siteTools=function(e){const o=Object.entries(e.resources??{}).map((([e,t])=>function(e,t){const o=e.indexOf("://");if(o>=0){const r=e.slice(o+3),n=r.indexOf("/"),s=n<0?r:r.slice(0,n),i=n<0?"":r.slice(n+1);return{raw:e,origin:`${e.slice(0,o).toLowerCase()}://${s.toLowerCase()}`,segments:i?i.split("/"):[],decl:t}}const r=e.replace(/^\/+/,"").replace(/\/+$/,"");return{raw:e,segments:r?r.split("/"):[],decl:t}}(e,t))),r=new Set(o.map((e=>e.origin)).filter((e=>void 0!==e))),n=new Map(Object.entries(e.commands??{}));if(n.has("xcall"))throw new Error("siteTools: `xcall` is built in; declare actions on resources instead");const s=(e,t)=>{const n=T(e,r);for(const r of o){const e=S(r,n.origin,n.segments);if(e)return{uri:n.text,pattern:r.raw,params:e,query:n.query,ctx:t,decl:r.decl}}y(`uri \`${e}\` is not a resource of this page; read uri="/" lists them`)},g=async(e,o)=>{var r;const g=(()=>{try{return m(e)}catch(t){y(`${t instanceof Error?t.message:String(t)}; exec runs one command, it is not a shell`)}})(),T="available commands: xcall"+(n.size?`, ${[...n.keys()].join(", ")}`:""),S=e.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g,"");x.test(S)&&y(`exec runs exactly one command and is not a shell: pipes, redirects, \`;\`, \`&\`, backquotes and \`$\` are not supported (quote them to pass them as text). ${T}`);const[w,...O]=g;if(w||y(`empty command; ${T}`),"xcall"===w){if(O.includes("--help")||O.includes("-h"))return`usage: ${h}\nThe actions of each resource are listed by read uri="/".`;const{object:e,action:n,params:i}=I(O),a=s(e,o),c=null==(r=a.decl.actions)?void 0:r[n];if(!c){const e=Object.keys(a.decl.actions??{});y(`resource \`${a.pattern}\` has no action \`${n}\` (actions: ${e.length?e.join(", "):"none"})`)}if(void 0!==c.input){const e=t.validateJson(c.input,i);e&&y(`invalid params for ${n}: ${e}`)}const{decl:l,...u}=a,p=await c.call(u,i);return`[risk: ${c.risk}]\n${b(E(p)||"ok",_).text}`}const A=n.get(w);let R;A||y(`unknown command \`${w}\`; exec runs one command, it is not a shell. ${T}`);try{const e=function(e,t,o){const r={},n=e.positionals??[],s=new Map((e.options??[]).map((e=>[e.name,e])));let m=0,f=!1;for(let g=0;g<t.length;){const e=t[g];if("--help"===e||"-h"===e){f=!0,g+=1;continue}if("--"===e){for(const e of t.slice(g+1))m=d(r,n,m,e);break}if(!e.startsWith("--")){m=d(r,n,m,e),g+=1;continue}const h=l(e),_=null==o?void 0:o(h,t,g);if(void 0!==_){g+=_;continue}const x=s.get(h.name);if(!x)throw new i("UNKNOWN_OPTION",`unknown option: --${h.name}`);const y=c(x);if(a(r,y))throw new i("DUPLICATE_ARGUMENT",`argument provided more than once: ${y}`);if("boolean"===x.type){if(void 0!==h.inlineValue)throw new i("INVALID_ARGUMENT",`--${h.name} does not accept a value`);r[y]=!0,g+=1;continue}const{value:T,consumed:S}=u(t,g,h);r[y]=p(x.type,T,h.name),g+=S}return{input:r,help:f,positionalCount:m}}({positionals:A.positionals,options:A.options},O);if(e.help)return $(w,A);for(let t=e.positionalCount;t<(A.positionals??[]).length;t++)if(!1!==(A.positionals??[])[t].required)throw new i("MISSING_ARGUMENT",`missing positional argument: ${(A.positionals??[])[t].name}`);for(const t of A.options??[]){const o=t.property??t.name.split("-").join("_");if(t.required&&!(o in e.input))throw new i("MISSING_ARGUMENT",`--${t.name} is required`)}R=e.input,A.inputSchema&&f(R,A.inputSchema,"input")}catch(N){throw N instanceof i&&y(`${w}: ${N.message}\n\n${$(w,A)}`),N}return b(E(await A.call(R,o))||"ok",_).text};return{read:{spec:{description:'Read a resource of this page by URI (GET). Start with uri "/": it lists the resources, their actions (with risk) and the commands. A collection\'s read is its list; filter and page with a query (notes?tag=x). Text comes in pages of lines: offset is the first line (1-based), limit the number of lines.',args_schema:N({uri:{type:"string",description:'Resource URI, e.g. "/" or "notes/1"'},offset:{type:"integer",description:"First line, 1-based"},limit:{type:"integer",description:"Number of lines"}},["uri"])},idempotent:!0,async call(e,t){const r=String(e.uri),i="number"==typeof e.offset?e.offset:void 0,a="number"==typeof e.limit?e.limit:void 0;if("/"===r.trim()||""===r.trim())return O((()=>{const e=['Resources (read uri="<resource>"; {name} is one path segment):'];for(const t of o){const o=["read","write","edit"].filter((e=>"edit"===e?!!(t.decl.edit||t.decl.read&&t.decl.write):!!t.decl[e]));e.push(`- ${t.raw} — ${t.decl.description} [${o.join(", ")||"no methods"}]`);for(const[r,n]of Object.entries(t.decl.actions??{}))e.push(` action ${r} (risk: ${n.risk}) — ${n.description}`)}0===o.length&&e.push("(none)"),e.push("",'Commands (exec "<command> --help" for usage):'),e.push(`- xcall — call an action of a resource: ${h}`);for(const[t,o]of n)e.push(`- ${t} — ${o.summary}`);return e.join("\n")})(),i,a);return O((await(async e=>{e.decl.read||y(`resource \`${e.pattern}\` cannot be read`);const{decl:t,...o}=e;return w(await e.decl.read(o))})(s(r,t))).text,i,a)}},write:{spec:{description:'Write a resource\'s content (PUT). mode: "write" (default) replaces it, "new" only creates it and fails if it exists, "append" adds to its end. Use edit to change part of it.',args_schema:N({uri:{type:"string",description:"Resource URI"},content:{type:"string",description:"The content"},mode:{type:"string",enum:["write","new","append"],description:"write | new | append"}},["uri","content"])},async call(e,t){const o=s(String(e.uri),t);o.decl.write||y(`resource \`${o.pattern}\` is read-only`);const{decl:r,...n}=o,i="string"==typeof e.mode?e.mode:"write";return E(await r.write(n,{content:String(e.content),mode:i}))||"written"}},edit:{spec:{description:"Change part of a resource (PATCH): old_string must occur exactly once in its current content and is replaced by new_string.",args_schema:N({uri:{type:"string",description:"Resource URI"},old_string:{type:"string",description:"Text to replace; must occur exactly once"},new_string:{type:"string",description:"Replacement text"}},["uri","old_string","new_string"])},async call(e,t){const o=s(String(e.uri),t),r={old_string:String(e.old_string),new_string:String(e.new_string)},{decl:n,...i}=o;if(n.edit)return E(await n.edit(i,r))||"edited";n.read&&n.write||y(`resource \`${o.pattern}\` cannot be edited`),r.old_string||y("old_string is empty");const a=w(await n.read(i)),c=a.text.split(r.old_string).length-1;0===c&&y("old_string was not found in the current content; read it again"),c>1&&y(`old_string occurs ${c} times; give more context so it occurs exactly once`);const l={content:a.text.replace(r.old_string,(()=>r.new_string)),mode:"write"};return void 0!==a.version&&(l.ifVersion=a.version),E(await n.write(i,l))||"edited"}},exec:{spec:{description:`Run one command (not a shell: no pipes, redirects, ;, &, backquotes or $). Built in: ${h} — calls an action listed by read uri="/". The page's commands are listed there too; "<command> --help" shows a command's usage.`,args_schema:N({command:{type:"string",description:"One command line"}},["command"])},idempotent:e=>function(e,t,o,r){var n,s,i;let a;try{a=m(e)}catch{return!1}const[c,...l]=a;if("xcall"===c)try{const{object:e,action:r}=I(l),i=T(e,o),a=t.find((e=>S(e,i.origin,i.segments))),c=null==(s=null==(n=null==a?void 0:a.decl.actions)?void 0:n[r])?void 0:s.risk;return"read_only"===c||"idempotent_write"===c}catch{return!1}const u=c?r.get(c):void 0;return"read"===(null==(i=null==u?void 0:u.access)?void 0:i.level)}(String(e.command??""),o,r,n),call:(e,t)=>g(String(e.command),t)}}};
|
|
2
2
|
//# sourceMappingURL=xllm.cjs.map
|
package/dist/xllm.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { X as XllmError, i as isObject } from "./aicc-
|
|
2
|
-
import { A, L, h, j, a, d, c, e, b, l, p, k, r, f, g, s } from "./aicc-
|
|
3
|
-
import { s as shellSettings, t as taskWaitMs, S as SiteToolManager, u as unresolvedReason, d as describeToolSource, a as utf8Length, v as validateJson, g as generateRunId, R as RUN_RECORD_VERSION } from "./site_manager-
|
|
4
|
-
import { a8, B, D, h as h2, i, j as j2, k as k2, l as l2, at, au, V, W, L as L2, e as e2, aj, a4, M, m, a5, av, G, Y, K, ae, z, b as b2, ak, x, aG, T, X, Z, _, $, ah, f as f2, aw, a9, y, A as A2, C, E, F, a0, af, ag, al, am, an, ao, o, ax, a6, H, J, aa, aA, aB, ab, I, aC, a1, a7, ap, a2, P, q, n, ac, w, p as p2, aq, ay, Q, az, N, r as r2, aD, U, a3, O, c as c2, ar, as, aE, ad, ai, aF } from "./site_manager-
|
|
1
|
+
import { X as XllmError, i as isObject } from "./aicc-286ba457.mjs";
|
|
2
|
+
import { A, L, h, j, a, d, c, e, b, l, p, k, r, f, g, s } from "./aicc-286ba457.mjs";
|
|
3
|
+
import { s as shellSettings, t as taskWaitMs, S as SiteToolManager, u as unresolvedReason, d as describeToolSource, a as utf8Length, v as validateJson, g as generateRunId, R as RUN_RECORD_VERSION } from "./site_manager-4f1940eb.mjs";
|
|
4
|
+
import { a8, B, D, h as h2, i, j as j2, k as k2, l as l2, at, au, V, W, L as L2, e as e2, aj, a4, M, m, a5, av, G, Y, K, ae, z, b as b2, ak, x, aG, T, X, Z, _, $, ah, f as f2, aw, a9, y, A as A2, C, E, F, a0, af, ag, al, am, an, ao, o, ax, a6, H, J, aa, aA, aB, ab, I, aC, a1, a7, ap, a2, P, q, n, ac, w, p as p2, aq, ay, Q, az, N, r as r2, aD, U, a3, O, c as c2, ar, as, aE, ad, ai, aF } from "./site_manager-4f1940eb.mjs";
|
|
5
5
|
import { D as D2, a as a10 } from "./did_object_client-c6dae827.mjs";
|
|
6
6
|
import "./krpc_client-673448e5.mjs";
|
|
7
7
|
import "./object_url-20e94b67.mjs";
|
package/dist/xllm_deno.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var t=Object.defineProperty,e=(e,n,r)=>(((e,n,r)=>{n in e?t(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r})(e,"symbol"!=typeof n?n+"":n,r),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./aicc-ccb36ef7.js"),r=require("./site_manager-70710895.js"),i=require("./openai-f560d518.js");function o(){const t=globalThis.Deno;if(!t)throw new Error("the xllm Deno host needs the Deno runtime");return t}function s(t){return t instanceof o().errors.NotFound}function a(t){return t instanceof o().errors.AlreadyExists}function c(t){return t instanceof Error?t.message:String(t)}function l(...t){let e="";for(const n of t)n&&(e=n.startsWith("/")||!e?n:e.endsWith("/")?e+n:`${e}/${n}`);return e}function u(t){const e=t.replace(/\/+$/,""),n=e.lastIndexOf("/");return n<0?".":0===n?"/":e.slice(0,n)}async function d(t){try{return(await o().stat(t)).isDirectory}catch{return!1}}async function h(t,e){const n=await o().open(t,{write:!0,create:!0,truncate:!0});try{let t=0;for(;t<e.length;)t+=await n.write(e.subarray(t));await n.sync()}finally{n.close()}}async function f(t){if("windows"===o().build.os)return;const e=await o().open(t,{read:!0});try{await e.sync()}finally{e.close()}}require("./krpc_client-26c2dc8b.js");const m=t=>t/2**32|0,p=t=>t>>>0;function w(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name&&"BYTES_PER_ELEMENT"in t&&1===t.BYTES_PER_ELEMENT}const g=t=>t?`"${t}" `:"";function y(t,e=""){if("number"!=typeof t)throw new TypeError(g(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(g(e)+"expected integer >= 0, got "+t);return t}function _(t,e,n=""){if(w(t)&&(void 0===e||t.length===e))return t;void 0!==e&&y(e,"length");const r=w(t),i=void 0!==e?` of length ${e}`:"",o=r?`length=${t.length}`:"type="+typeof t,s=g(n)+"expected Uint8Array"+i+", got "+o;if(!r)throw new TypeError(s);throw new RangeError(s)}const v=(t,e)=>{((t,e)=>{if(null===t||"object"!=typeof t||Array.isArray(t))throw new TypeError(("object"===e?"":`"${e}" `)+"expected object, got type="+typeof t)})(t,e);const n=Object.getPrototypeOf(t);if(n!==Object.prototype&&null!==n)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function b(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function $(t,e){_(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function k(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function x(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function E(t,e){return t<<32-e|t>>>e}const O=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function I(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const S=O?t=>t:t=>I(t)>>>0;const T=O?t=>t:function(t){for(let e=0;e<t.length;e++)t[e]=I(t[e]);return t},A=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),L=Array.from({length:256},((t,e)=>e.toString(16).padStart(2,"0")));function P(t,e,n="opts"){v(t,"defaults"),void 0!==e&&v(e,n);return Object.assign(Object.create(null),t,e)}function R(t,e={}){if("function"!=typeof t)throw new TypeError('"hashCons" expected function, got type='+typeof t);e=P({},e,"info");const n=(e,n)=>t(n).update(e).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=e=>t(e),Object.assign(n,e),Object.freeze(n)}const D=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);function M(t,e,n,r,i){return r=E(r^(t=t+e+i|0),16),{a:t,b:e=E(e^(n=n+r|0),12),c:n,d:r}}function X(t,e,n,r,i){return r=E(r^(t=t+e+i|0),8),{a:t,b:e=E(e^(n=n+r|0),7),c:n,d:r}}class j{constructor(t,n){e(this,"buffer"),e(this,"buffer32"),e(this,"finished",!1),e(this,"destroyed",!1),e(this,"length",0),e(this,"pos",0),e(this,"blockLen"),e(this,"outputLen"),e(this,"canXOF",!1),y(t),y(n),this.blockLen=t,this.outputLen=n,this.buffer=new Uint8Array(t),this.buffer32=k(this.buffer)}update(t){b(this),_(t);const{blockLen:e,buffer:n,buffer32:r}=this,i=t.length,o=t.byteOffset,s=t.buffer;for(let a=0;a<i;){this.pos===e&&(T(r),this.compress(r,0,!1),T(r),this.pos=0);const c=Math.min(e-this.pos,i-a),l=o+a;if(c!==e||l%4||!(a+c<i))n.set(0===a&&c===i?t:t.subarray(a,a+c),this.pos),this.pos+=c,this.length+=c,a+=c;else{const t=new Uint32Array(s,l,Math.floor((i-a)/4));T(t);for(let n=0;a+e<i;n+=r.length,a+=e)this.length+=e,this.compress(t,n,!1);T(t)}}return this}digestInto(t){if(b(this),$(t,this),3&t.byteOffset)throw new RangeError('"output" expected 4-byte aligned byteOffset, got '+t.byteOffset);const{pos:e,buffer32:n}=this;this.finished=!0,this.buffer.fill(0,e),T(n),this.compress(n,0,!0),T(n);const r=this.get(),i=t===this.buffer?n:k(t),o=Math.floor(this.outputLen/4);for(let l=0;l<o;l++)i[l]=S(r[l]);const s=this.outputLen%4;if(!s)return;const a=4*o,c=r[o];for(let l=0;l<s;l++)t[a+l]=c>>>8*l}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){const{buffer:e,length:n,finished:r,destroyed:i,outputLen:o,pos:s}=this;return t||(t=new this.constructor({dkLen:o})),t.set(...this.get()),t.buffer.set(e),t.destroyed=i,t.finished=r,t.length=n,t.pos=s,t.outputLen=o,t}clone(){return this._cloneInto()}}function N(t,e,n,r,i,o,s,a,c,l,u,d,h,f,m,p,w,g,y,_){let v=0;for(let b=0;b<r;b++)({a:i,b:c,c:h,d:w}=M(i,c,h,w,n[e+t[v++]])),({a:i,b:c,c:h,d:w}=X(i,c,h,w,n[e+t[v++]])),({a:o,b:l,c:f,d:g}=M(o,l,f,g,n[e+t[v++]])),({a:o,b:l,c:f,d:g}=X(o,l,f,g,n[e+t[v++]])),({a:s,b:u,c:m,d:y}=M(s,u,m,y,n[e+t[v++]])),({a:s,b:u,c:m,d:y}=X(s,u,m,y,n[e+t[v++]])),({a:a,b:d,c:p,d:_}=M(a,d,p,_,n[e+t[v++]])),({a:a,b:d,c:p,d:_}=X(a,d,p,_,n[e+t[v++]])),({a:i,b:l,c:m,d:_}=M(i,l,m,_,n[e+t[v++]])),({a:i,b:l,c:m,d:_}=X(i,l,m,_,n[e+t[v++]])),({a:o,b:u,c:p,d:w}=M(o,u,p,w,n[e+t[v++]])),({a:o,b:u,c:p,d:w}=X(o,u,p,w,n[e+t[v++]])),({a:s,b:d,c:h,d:g}=M(s,d,h,g,n[e+t[v++]])),({a:s,b:d,c:h,d:g}=X(s,d,h,g,n[e+t[v++]])),({a:a,b:c,c:f,d:y}=M(a,c,f,y,n[e+t[v++]])),({a:a,b:c,c:f,d:y}=X(a,c,f,y,n[e+t[v++]]));return{v0:i,v1:o,v2:s,v3:a,v4:c,v5:l,v6:u,v7:d,v8:h,v9:f,v10:m,v11:p,v12:w,v13:g,v14:y,v15:_}}const U=1,C=2,F=4,H=8,B=16,z=32,q=64,W=D.slice(),J=(()=>{const t=Array.from({length:16},((t,e)=>e)),e=t=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((e=>t[e])),n=[];for(let r=0,i=t;r<7;r++,i=e(i))n.push(...i);return Uint8Array.from(n)})();class G extends j{constructor(t={},n=0){super(64,void 0===(t=P({},t)).dkLen?32:t.dkLen),e(this,"canXOF",!0),e(this,"chunkPos",0),e(this,"chunksDone",0),e(this,"flags",0),e(this,"IV"),e(this,"state"),e(this,"stack",[]),e(this,"posOut",0),e(this,"bufferOut32",new Uint32Array(16)),e(this,"bufferOut"),e(this,"chunkOut",0),e(this,"enableXOF",!0);const{key:r,context:i}=t,o=void 0!==i;if(void 0!==r){if(o)throw new Error('cannot use both "key" and "context"');_(r,32,"key");const t=(s=r,Uint8Array.from(_(s)));this.IV=k(t),T(this.IV),this.flags=n|B}else if(o){_(i,void 0,"context");const t=i,e=new G({dkLen:32},z).update(t).digest();this.IV=k(e),T(this.IV),this.flags=n|q}else this.IV=W,this.flags=n;var s,a;this.state=this.IV.slice(),this.bufferOut=(a=this.bufferOut32,new Uint8Array(a.buffer,a.byteOffset,a.byteLength))}get(){return[]}set(){}b2Compress(t,e,n,r=0){const{state:i,pos:o}=this,s=p(t),a=m(t),{v0:c,v1:l,v2:u,v3:d,v4:h,v5:f,v6:w,v7:g,v8:y,v9:_,v10:v,v11:b,v12:$,v13:k,v14:x,v15:E}=N(J,r,n,7,i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7],W[0],W[1],W[2],W[3],s,a,o,e);i[0]=c^y,i[1]=l^_,i[2]=u^v,i[3]=d^b,i[4]=h^$,i[5]=f^k,i[6]=w^x,i[7]=g^E}compress(t,e=0,n=!1){let r=this.flags;if(this.chunkPos||(r|=U),(15===this.chunkPos||n)&&(r|=C),n||(this.pos=this.blockLen),this.b2Compress(this.chunksDone,r,t,e),this.chunkPos+=1,16===this.chunkPos||n){let t=this.state;this.state=this.IV.slice();for(let e,r=this.chunksDone+1;(n||!(1&r))&&(e=this.stack.pop());r=Math.floor(r/2))this.buffer32.set(e,0),this.buffer32.set(t,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|F,this.buffer32,0),t=this.state,this.state=this.IV.slice();this.chunksDone++,this.chunkPos=0,this.stack.push(t)}this.pos=0}_cloneInto(t){const e=!!t&&t.finished&&!t.destroyed;t=super._cloneInto(t);const{IV:n,flags:r,state:i,chunkPos:o,posOut:s,chunkOut:a,stack:c,chunksDone:l}=this;return t.state.set(i),t.stack=c.map((t=>Uint32Array.from(t))),n===W?(t.IV!==W&&x(t.IV),t.IV=W):t.IV===W?t.IV=n.slice():t.IV.set(n),t.flags=r,t.chunkPos=o,t.chunksDone=l,t.posOut=s,t.chunkOut=a,t.enableXOF=this.enableXOF,this.finished?t.bufferOut32.set(this.bufferOut32):e&&x(t.bufferOut32),t}destroy(){this.destroyed=!0,x(this.state,this.buffer32,this.bufferOut32),this.IV!==W&&x(this.IV),x(...this.stack)}b2CompressOut(){const{state:t,pos:e,flags:n,buffer32:r,bufferOut32:i}=this,o=this.chunkOut++,s=p(o),a=m(o);T(r);const{v0:c,v1:l,v2:u,v3:d,v4:h,v5:f,v6:w,v7:g,v8:y,v9:_,v10:v,v11:b,v12:$,v13:k,v14:x,v15:E}=N(J,0,r,7,t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],W[0],W[1],W[2],W[3],s,a,e,n);i[0]=c^y,i[1]=l^_,i[2]=u^v,i[3]=d^b,i[4]=h^$,i[5]=f^k,i[6]=w^x,i[7]=g^E,i[8]=t[0]^y,i[9]=t[1]^_,i[10]=t[2]^v,i[11]=t[3]^b,i[12]=t[4]^$,i[13]=t[5]^k,i[14]=t[6]^x,i[15]=t[7]^E,T(r),T(i),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,this.buffer.fill(0,this.pos);let t=this.flags|H;this.stack.length?(t|=F,T(this.buffer32),this.compress(this.buffer32,0,!0),T(this.buffer32),this.chunksDone=0,this.pos=this.blockLen):t|=(this.chunkPos?0:U)|C,this.flags=t,this.b2CompressOut()}writeInto(t){b(this,!1),_(t),this.finish();const{blockLen:e,bufferOut:n}=this;for(let r=0,i=t.length;r<i;){this.posOut>=e&&this.b2CompressOut();const o=Math.min(e-this.posOut,i-r);t.set(n.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return t}xofInto(t){if(!this.enableXOF)throw new Error("no XOF after digest()");return this.writeInto(t)}xof(t){return y(t),this.xofInto(new Uint8Array(t))}digestInto(t){if($(t,this),this.finished)throw new Error("digest() was already called");this.enableXOF=!1,this.writeInto(t.length===this.outputLen?t:t.subarray(0,this.outputLen)),this.destroy()}digest(){const t=new Uint8Array(this.outputLen);return this.digestInto(t),t}}const V=R(((t={})=>new G(t))),K="AGENT_TOOL_HOST_ID";function Y(t){return function(t){if(_(t),A)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=L[t[n]];return e}(V((new TextEncoder).encode(t)))}async function Z(t){try{return await o().readTextFile(t)}catch{return null}}function Q(t){var e;const n=null==(e=t.agent_tool_host_id)?void 0:e.trim();if(n)return`host:${n}:`;return`host:${(t.etc_hostname??t.hostname_env??"unknown").trim()}:${(t.machine_id??"").trim()}`}async function tt(){const t=o().env.get(K)??null;return(null==t?void 0:t.trim())?Q({agent_tool_host_id:t,etc_hostname:null,hostname_env:null,machine_id:null}):Q({agent_tool_host_id:t,etc_hostname:await Z("/etc/hostname"),hostname_env:o().env.get("HOSTNAME")??null,machine_id:await Z("/etc/machine-id")})}function et(t,e){return{host:t,uid:e}}function nt(t){return n.canonicalJson(t)}function rt(t,e,n){return t??it(e,n)}function it(t,e){return`${t}:${Y(nt(e)).slice(0,24)}`}function ot(t,e){return l(t,`${Y(e).slice(0,24)}.lock`)}const st="read_file",at="write_file",ct="edit_file",lt="shell",ut=[st,at,ct,lt],dt=61440,ht=2048,ft="native",mt=4*r.RESULT_BUDGET_TOKENS-2048;class pt extends Error{constructor(t,e,n=!1){super("invalid_args"===t?`invalid args: ${e}`:"exec_failed"===t?`execution failed: ${e}`:"timeout"===t?"timeout":"transport"===t?`runtime transport: ${e}`:`cancelled: ${e}`),this.kind=t,this.detail=e,this.effectUnknown=n,this.name="NativeToolError"}}const wt=t=>new pt("invalid_args",t),gt=t=>new pt("exec_failed",t);function yt(t){const e=[];let n="",r=!1,i=!1;const o=[...t];for(let s=0;s<o.length;s++){const t=o[s];"'"!==t||i?'"'!==t||r?"\\"!==t||r?!/\s/.test(t)||r||i?n+=t:n&&(e.push(n),n=""):s+1<o.length&&(n+=o[++s]):i=!i:r=!r}if(!r&&!i)return n&&e.push(n),e}function _t(t){var e;const n=void 0!==t.cmd_name?(null==(e=t.cmd_args)?void 0:e.trim())?`${t.cmd_name} ${t.cmd_args.trim()}`:t.cmd_name:void 0;return`${(void 0!==n?function(t,e){const n=[...t];return n.length<=e?t:`${n.slice(0,e).join("")}...[TRUNCATED]`}(n.trim(),96):"")||"action"} => ${"pending"===t.status?void 0!==t.pending_reason?`pending (${t.pending_reason})`:"pending":t.status}`}function vt(t,e,n,r){const i={agent_tool_protocol:"1",tool:t,status:"success",summary:r,detail:e},o=yt(n),s=o&&o.length?o:n.split(/\s+/).filter(Boolean);return s.length&&(i.cmd_name=s[0],s.length>1&&(i.cmd_args=s.slice(1).join(" "))),i.title=_t(i),i}function bt(t,e){return e.trim()?t.output=e:delete t.output,t}function $t(t,e){return"/"===e?t.startsWith("/"):t===e||t.startsWith(`${e}/`)}function kt(t,e){if(0!==e.length&&!e.some((e=>$t(t,e))))throw wt(`path not allowed by policy: ${t}`)}async function xt(t){let e=t.replace(/\/+$/,"")||"/";const n=[];for(;;)try{const t=await o().realPath(e);return r.normalizePath(l(t,...n.slice().reverse()))}catch(i){if(!s(i))throw gt(c(i));try{throw await o().lstat(e),wt(`dangling symlink: ${e}`)}catch(a){if(a instanceof pt)throw a}const r=e.slice(e.lastIndexOf("/")+1);if(!r||".."===r)throw wt(`cannot resolve ${t}`);"."!==r&&n.push(r);const l=u(e);if(l===e||"/"===e)throw wt("path has no existing ancestor");e=l}}async function Et(t,e,n){if(!e.trim())throw wt("path cannot be empty");const i=e.startsWith("/")?e:l(t,e);kt(r.normalizePath(i),n);const o=await xt(i);return kt(o,await Promise.all(n.map(xt))),o}function Ot(t){let e="";for(const n of(new TextEncoder).encode(t)){const t=String.fromCharCode(n);e+=/[A-Za-z0-9\-._~!$&'()*+,;=:@]/.test(t)?t:`%${n.toString(16).toUpperCase().padStart(2,"0")}`}return e}function It(t,e){if(!t)return;const n=r.normalizePath(t);if(!$t(e,n))return;return`cyfs://${["",...e.slice(n.length).split("/").filter((t=>t&&"."!==t))].map(Ot).join("/")||"/"}`}function St(t){return null===t?"null":"boolean"==typeof t?`boolean \`${t}\``:"number"==typeof t?Number.isInteger(t)?`integer \`${t}\``:`floating point \`${t}\``:"string"==typeof t?`string ${JSON.stringify(t)}`:Array.isArray(t)?"sequence":"map"}function Tt(t,e){return wt(`invalid args for \`${t}\`: ${e}`)}function At(t,e,n){const r=e[n];if(void 0===r)throw Tt(t,`missing field \`${n}\``);if("string"!=typeof r)throw Tt(t,`invalid type: ${St(r)}, expected a string`);return r}function Lt(t,e,n){const r=e[n];if(null!=r){if("string"!=typeof r)throw Tt(t,`invalid type: ${St(r)}, expected a string`);return r}}const Pt=new TextEncoder;function Rt(t){return Pt.encode(t).length}function Dt(t){return new TextDecoder("utf-8",{ignoreBOM:!0}).decode(t)}function Mt(t){return t?t.match(/[^\n]*\n|[^\n]+$/g)??[]:[]}function Xt(t){if(!t)return[];const e=t.split("\n");return""===e[e.length-1]&&e.pop(),e.map((t=>t.endsWith("\r")?t.slice(0,-1):t))}function jt(t){return t.replace(/[\r\n]+$/,"")}function Nt(t){const e=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\r/g,"\\r").replace(/\n/g,"\\n"),n=t?Math.max(Xt(t).length,1):0,r=[...e];return r.length<=64?e:`${r.slice(0,32).join("")}...(total ${n} lines)...${r.slice(-32).join("")}`}function Ut(t,e){const n=t.trim();if("$"===n)return"end";if(n.startsWith("+")||!/^-?\d+$/.test(n))throw wt(`invalid range text \`${e}\``);const r=Number(n);if(0===r)throw wt("range must be 1-based, zero is invalid");return r}function Ct(t,e){const n=t.trim();if(!n.startsWith("+"))throw wt(`invalid range text \`${e}\``);const r=n.slice(1).trim();if(!/^\d+$/.test(r))throw wt(`invalid range text \`${e}\``);const i=Number(r);if(0===i)throw wt("range count must be positive integer");return i}function Ft(t,e){if("string"==typeof t)return Ut(t,e);if("number"==typeof t&&Number.isInteger(t)){if(0===t)throw wt(`${e} must be non-zero integer`);return t}throw wt(`${e} must be integer or \`$\``)}function Ht(t){if(null!=t){if(n.isObject(t)){const e=void 0!==t.start?Ft(t.start,"range.start"):void 0,n=void 0!==t.end?Ft(t.end,"range.end"):void 0,r=void 0!==t.count?function(t,e){if("number"!=typeof t||!Number.isInteger(t)||t<=0)throw wt(`${e} must be positive integer`);return t}(t.count,"range.count"):void 0;if(void 0!==r&&void 0!==n)throw wt("range cannot set both `end` and `count`");if(void 0!==r&&void 0===e)throw wt("range.count requires range.start");if(void 0===e&&void 0===n&&void 0===r)throw wt("range object must contain at least one of start/end/count");return{start:e,end:n,count:r,defaultEnd:"tail_if_start_negative"}}if(Array.isArray(t)){if(0===t.length||t.length>2)throw wt("range array must be [start] or [start,end]");return{start:Ft(t[0],"range[0]"),end:2===t.length?Ft(t[1],"range[1]"):void 0,defaultEnd:"same_as_start"}}if("number"==typeof t&&Number.isInteger(t))return{start:Ft(t,"range"),defaultEnd:"same_as_start"};if("string"==typeof t)return function(t){const e=t.trim();if(!e||"-"===e)return;if(e.includes(",")||e.includes(":")){if(e.includes(",")&&e.includes(":"))throw wt(`invalid range text \`${t}\``);const n=e.split(e.includes(",")?",":":");if(2!==n.length)throw wt(`invalid range text \`${t}\``);const r=n[0].trim()?Ut(n[0].trim(),t):void 0,i=n[1].trim();if(i.startsWith("+")){if(void 0===r)throw wt(`range \`${t}\` with \`+count\` requires start`);return{start:r,count:Ct(i,t),defaultEnd:"same_as_start"}}return{start:r,end:i?Ut(i,t):void 0,defaultEnd:"end"}}const n=e.indexOf("-");if(n>=0){const r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(r&&i&&/^\d+$/.test(r)&&/^\d+$/.test(i))return{start:Ut(r,t),end:Ut(i,t),defaultEnd:"same_as_start"}}return{start:Ut(e,t),defaultEnd:"same_as_start"}}(t);throw wt("range must be string/number/array/object")}}function Bt(t,e){return"end"===t?e:t>0?t:e+t+1}const zt={name:st,description:'Read a text file. range selects 1-based lines ("120-200", "120:$", "120:+20", "-50:$" for the last 50); first_chunk starts the read at the first occurrence of that text. Paths are relative to the working directory; paths outside it only where the run\'s filesystem policy allows.',args_schema:{properties:{first_chunk:{description:"Start the read at the first occurrence of this text (range then counts from there).",type:"string"},path:{description:"File to read, relative to the working directory.",type:"string"},range:{description:'1-based line range: "120-200", "120:$" (to the end), "120:+20" (20 lines from 120); negative numbers count from the end ("-50:$").'}},required:["path"],type:"object"}},qt={name:at,description:'Write a text file: mode "write" (default) creates or overwrites it, "append" adds to its end, "new" creates it and fails if it exists. Parent directories are created. Paths are relative to the working directory; paths outside it only where the run\'s filesystem policy allows.',args_schema:{properties:{content:{description:"The text to write.",type:"string"},mode:{description:"`write` (default): create or overwrite; `append`: add to the end; `new`: create, fail if the file exists.",type:"string"},path:{description:"File to write, relative to the working directory.",type:"string"}},required:["content","path"],type:"object"}},Wt={name:ct,description:"Replace the one exact occurrence of old_string with new_string in a text file. Fails when old_string is absent or occurs more than once: include enough surrounding text to make it unique. Paths are relative to the working directory; paths outside it only where the run's filesystem policy allows.",args_schema:{properties:{new_string:{description:"The replacement text.",type:"string"},old_string:{description:"The exact text to replace; it must occur exactly once.",type:"string"},path:{description:"File to edit, relative to the working directory.",type:"string"}},required:["new_string","old_string","path"],type:"object"}};async function Jt(t){try{return await o().readFile(t)}catch(e){throw gt(`read file failed: ${c(e)}`)}}async function Gt(t){return Dt(await Jt(t))}async function Vt(t,e){try{await o().mkdir(u(t),{recursive:!0})}catch(n){throw gt(c(n))}try{await o().writeFile(t,Pt.encode(e))}catch(n){throw gt(`write file failed: ${c(n)}`)}}function Kt(t){return{spec:zt,idempotent:!0,cancellable:!1,async call(e){const i=At(st,e,"path"),o=Lt(st,e,"first_chunk"),s=null===e.range?void 0:e.range,a=i.trim();if(!a)throw wt("missing required arg `path`");const c=await Et(t.root,a,t.allowedRead),l=await Jt(c);if(function(t){return t.subarray(0,8192).includes(0)}(l))throw wt(`\`${a}\` is a binary file (${l.length} bytes): read_file only reads text. Use llm_understand_media for images, PDFs and office documents, or a shell command that converts or inspects the format.`);const u=Dt(l);let d,h=!0,f=1;if(void 0!==o){const t=u.indexOf(o);t>=0?(d=u.slice(t),f=(u.slice(0,t).match(/\n/g)??[]).length+1):(d="",h=!1)}else d=u;const m=Mt(d),p=m.length,w=Ht(s);let g,y,_="";w?([g,y]=function(t,e){const n=t.start??1,r=Bt(n,e);let i;return i=void 0!==t.count?r+t.count-1:void 0!==t.end?Bt(t.end,e):"same_as_start"===t.defaultEnd?r:"end"===t.defaultEnd||"number"==typeof n&&n<0?e:r,[Math.min(Math.max(r,1),e+1),Math.min(Math.max(i,0),e)]}(w,p),_=`${g}-${y}`):0===p?(g=1,y=0):(g=1,y=p);const v=Math.min(Math.max(g-1,0),p),b=Math.min(y,p),$=v<b?m.slice(v,b):[],k=$.join(""),x=$.length,E=0===x?null:f+v,O=null===E?null:E+Math.max(x-1,0),I=function(t,e,n){const r={text:"",shown:0};if(null===t)return r;let i=0;for(let o=0;o<Math.min(e.length,200);o++){const s=t+o,a=jt(e[o]),c=`${s}: `,l=o>0?1:0,u=Rt(a);if(i+l+c.length+u>n){if(0===o){const t=(new TextEncoder).encode(a);let e=Math.min(Math.max(n-c.length,0),t.length);for(;e>0&&e<t.length&&128==(192&t[e]);)e--;r.text=c+(new TextDecoder).decode(t.subarray(0,e)),r.shown=1,r.cut=[s,e,t.length]}break}l&&(r.text+="\n"),r.text+=c+a,i+=l+c.length+u,r.shown++}return r}(E,$,mt),S=Rt(k),T=function(t,e,r){let i=`${st} ${t}`;if(void 0!==e&&(i+=` first_chunk="${Nt(e)}"`),null!=r){const t="string"==typeof r?r:n.canonicalJson(r);t.trim()&&(i+=` range=${t}`)}return i}(a,o,s),A=Mt(u).length,L=null!==E&&I.shown>0?E+I.shown-1:null,P=()=>{if(null===O||null===E)return;const t=null===L?E:L+1;return t<=O?[t,O]:void 0},R=()=>null!==L&&void 0===P()&&void 0===I.cut&&L<A?L:void 0;let D;if(h)if(null===L)D=`${a}: read 0 lines (the file has ${1===A?"1 line":`${A} lines`})`;else{D=`${a}: shown lines ${E}–${L} of ${A} (${S} bytes read)`,I.cut&&(D+=`; line ${I.cut[0]} cut at ${I.cut[1]} of ${I.cut[2]} bytes`);const t=P();t&&(D+=`; lines ${t[0]}–${t[1]} not shown`)}else D=`first_chunk was not found in ${a}: nothing read`;const M={path:c},X=It(t.dfsRoot,c);void 0!==X&&(M.cyfs_url=X),Object.assign(M,{content:k,matched:h,line_range:_,bytes:S,line_count:x,total_lines:A,start_line:E,end_line:O,preview_truncated:I.shown<x||void 0!==I.cut});const j=vt(st,M,T,D);if(j.title=`${T} => ${h?"success":"anchor not found"}`,I.text){let t=I.text;if(I.cut){const[e,n,r]=I.cut;t+=`\n[line ${e} has ${r} bytes, the first ${n} are shown`,c.startsWith("/")&&(t+=`; read the rest with a command such as \`sed -n '${e}p' ${c} | cut -b ${n+1}-${n+mt}\``),t+="]"}const e=P(),n=void 0!==o?" and without first_chunk (these are lines of the whole file)":"",r=Math.max(I.shown,1);if(e)t+=`\n[lines ${e[0]}–${e[1]} not shown: read again with range=${e[0]}-${Math.min(e[1],e[0]+r-1)}${n}]`;else if(void 0!==R()){const e=R();t+=`\n[shown lines ${E??e}–${e} of ${A}; the next lines: range=${e+1}-${Math.min(A,e+r)}${n}]`}bt(j,t)}return(P()||I.cut||void 0!==R())&&(j.hints=[{text:'`range` reads any part: "201-400", "201:+200" (200 lines from 201), "-50:$" (the last 50). Line numbers are those of the whole text.',once:"read.paging"}]),function(t,e){if("success"!==t.status||!n.isObject(t.detail))return t;const i=t.detail,o="string"==typeof i.path?i.path:e,s=t=>"number"==typeof i[t]?String(i[t]):"";return t.dedup={key:`read:${o}#${s("start_line")}-${s("end_line")}::${Y(r.observationText(t)).slice(0,16)}`,hint:`\`${e}\` is unchanged`},t}(j,a)}}}function Yt(t){const e=(t??"write").trim().toLowerCase();if("new"===e||"create"===e)return"new";if("append"===e)return"append";if(""===e||"write"===e||"overwrite"===e)return"write";throw wt(`invalid write mode \`${e}\`, expected new/append/write`)}function Zt(t){return{spec:qt,idempotent:!1,cancellable:!1,async call(e){const n=At(at,e,"path"),r=At(at,e,"content"),i=Lt(at,e,"mode");let a;try{a=Yt(i)}catch{a="write"}const l=`${at} ${n} mode=${a}`,u=n.trim();if(!u)throw wt("missing required arg `path`");const d=Yt(i),h=await Et(t.root,u,t.allowedWrite),f=await async function(t){try{return await o().stat(t),!0}catch(e){if(s(e))return!1;throw gt(c(e))}}(h);if("new"===d&&f)throw wt(`write mode \`new\` requires target file not exist: ${u}`);const m=f?await Gt(h):"",p="append"===d?"append":"new"===d?"new":f?"write":"create",w="append"===d?`${m}${r}`:r;await Vt(h,w);const g=Mt(r).length,y={},_=It(t.dfsRoot,h);void 0!==_&&(y.cyfs_url=_);const v=Rt(w);Object.assign(y,{created:!f,changed:m!==w,bytes_written:v,line_count:g});const b=`${"append"===p?"appended":"new"===p||"create"===p?"created":"wrote"} ${u}, wrote ${Rt(r)} bytes across ${1===g?"1 line":`${g} lines`}`,$=vt(at,y,l,b),k="append"===p?"append":"new"===p||"create"===p?"new":"write";return $.title=`${at} ${u} mode=${k} => success (${v} bytes)`,$}}}function Qt(t){return{spec:Wt,idempotent:!1,cancellable:!1,async call(e){const n=At(ct,e,"path"),r=At(ct,e,"old_string"),i=At(ct,e,"new_string"),o=`${ct} ${n} old_string="${Nt(r)}"`,s=n.trim();if(!s)throw wt("missing required arg `path`");if(!r)throw wt("missing required arg `old_string`");if(r===i)throw wt("`new_string` must be different from `old_string`");const a=await Et(t.root,s,t.allowedWrite),c=await Gt(a),l=[];for(let t=c.indexOf(r);t>=0;t=c.indexOf(r,t+r.length))l.push(t);if(0===l.length)throw wt("`old_string` was not found in the file");if(l.length>1)throw wt(`\`old_string\` must match exactly once, found ${l.length} matches`);const u=l[0],d=c.slice(0,u)+i+c.slice(u+r.length),h=c!==d;h&&await Vt(a,d);const f=function(t,e,n){const r=Xt(e),i=Xt(n),o=[];for(let s=0;s<Math.max(r.length,i.length);s++){const t=r[s],e=i[s];void 0!==t&&void 0!==e?t===e?o.push(` ${t}`):o.push(`-${t}`,`+${e}`):void 0!==t?o.push(`-${t}`):void 0!==e&&o.push(`+${e}`)}return[`--- a/${t}`,`+++ b/${t}`,`@@ -1,${r.length} +1,${i.length} @@`,...o].join("\n")}(s,c,d),m=(c.slice(0,u).match(/\n/g)??[]).length+1,p={},w=It(t.dfsRoot,a);void 0!==w&&(p.cyfs_url=w),Object.assign(p,{matched:!0,changed:h,mode:"replace",line:m,diff:f,diff_truncated:!1});const g=vt(ct,p,o,h?`edited ${s} with replace at line ${m}`:`edit ${s} made no change`);return h&&f.trim()&&bt(g,f),g.title=`${ct} ${s} => ${h?`success (line ${m})`:"no change"}`,g}}}const te='if [ "$#" -ge 2 ]; then export PATH="$2"; fi\nprintf \'%s\\n\' "$0" > "$1/command"\n"$BASH" -c "$0" </dev/null >"$1/stdout" 2>"$1/stderr"\n__llm_ec=$?\nprintf \'%s\\n\' "$__llm_ec" > "$1/exit.tmp" && command -p mv -f "$1/exit.tmp" "$1/exit"\nexit $__llm_ec',ee=["/usr/local/sbin","/usr/local/bin","/usr/sbin","/usr/bin","/sbin","/bin"];function ne(t){const e=[...t].map((t=>/[A-Za-z0-9\-_.]/.test(t)?t:"_")).join("");return!e||e.startsWith(".")?`c_${e}`:e}function re(t,e){if(t&&e)return l(t,"exec",ne(e))}function ie(t){const e=Math.floor(t/1e3);return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${String(e%60).padStart(2,"0")}s`:`${Math.floor(e/3600)}h${String(Math.floor(e%3600/60)).padStart(2,"0")}m`}function oe(t,e,n){const r=Math.floor(e/4),i=e-r,o=t.subarray(0,Math.min(r,t.length)),s=t.subarray(o.length),a=s.subarray(Math.max(0,s.length-i));if(!(t.length>o.length+a.length))return[Dt(o)+Dt(a),!1];const c=t.length-o.length-a.length,l=void 0===n?`…[${c} bytes omitted]…`:`…[${c} bytes omitted; full ${n.split("/").pop()||"output"}: ${n}]…`;return[`${Dt(o)}\n${l}\n${Dt(a)}`,!0]}async function se(t){try{return await o().readFile(t)}catch{return}}async function ae(t,e){const n=await se(t);return n?Dt(n.subarray(Math.max(0,n.length-e))):""}async function ce(t){try{const e=(await o().readTextFile(l(t,"exit"))).trim();return/^[+-]?\d+$/.test(e)?Number(e):void 0}catch{return}}async function le(t,e,n,r,i,o,s){const a=l(t,"stdout"),c=l(t,"stderr"),u=await se(a)??new Uint8Array,d=await se(c)??new Uint8Array,[h,f]=function(t,e,n){if(t+e<=n)return[t,e];const r=Math.floor(n/2);return t<=r?[t,n-t]:e<=r?[n-e,e]:[r,n-r]}(u.length,d.length,i),[m,p]=oe(u,Math.max(h,16),s?a:void 0),[w,g]=oe(d,Math.max(f,16),s?c:void 0);let y=m;return w&&(y&&!y.endsWith("\n")&&(y+="\n"),y+=w),{exit_code:e,stdout:m,stderr:w,output:y,output_truncated:p||g,timed_out:n,duration_ms:Math.floor(r),cwd:o}}const ue={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGBUS:7,SIGFPE:8,SIGKILL:9,SIGUSR1:10,SIGSEGV:11,SIGUSR2:12,SIGPIPE:13,SIGALRM:14,SIGTERM:15};const de=["tool","cmd_name","task_id","pending_reason","estimated_wait","title","summary","cmd_args","partial_output","output"];function he(t){const e=t.maxTimeoutMs,n=`Run a command in this run's runtime (native) with bash syntax. It starts in the working directory unless cwd is given; it is not sandboxed and runs with the current user's permissions. The command is a child process of this executor: an interrupt or a timeout ends its process group; processes it leaves behind after returning are not managed. Waits for the command to finish. Default timeout ${Math.floor(t.timeoutMs/1e3)}s${0===e?", no upper limit":`, max ${Math.floor(e/1e3)}s`}; on timeout the command is stopped and the output so far is returned. Start a long-lived service with nohup / setsid and return at once; on Unix, processes started with \`&\` / nohup in the foreground command's process group also end when that command is interrupted or times out. Long output keeps its beginning and end.`,r={description:`Timeout in milliseconds (default ${t.timeoutMs}${0===e?"":`, max ${e}`}). Set it explicitly for long builds, tests or media commands.`,minimum:1,type:"integer"};return 0!==e&&(r.maximum=e),{name:lt,description:n,args_schema:{properties:{command:{description:"bash command to execute",type:"string"},cwd:{description:t.restrictCwd?"Working directory, relative to or within the configured workspace. Defaults to the workspace.":"Working directory, absolute or relative to the default working directory. Defaults to that directory; outside paths are allowed subject to OS permissions.",type:"string"},timeout_ms:r},required:["command"],type:"object"}}}function fe(t,e){if(null!=t){if("number"==typeof t&&Number.isInteger(t)&&t>=0)return t;if("string"==typeof t&&/^\d+$/.test(t.trim()))return Number(t.trim());throw wt(`\`${e}\` must be a non-negative integer`)}}let me=0;function pe(t){let e;return{done:new Promise((n=>{e=setTimeout((()=>n("timeout")),Math.min(t,2**31-1))})),stop:()=>clearTimeout(e)}}function we(t){return{spec:he(t),idempotent:!1,cancellable:!0,async call(e,i){const s="string"==typeof e.command?e.command.trim():"";if(!s)throw wt("`command` is required and must be non-empty");const a="string"==typeof e.cwd?e.cwd:void 0,u=r.normalizePath(t.workspace),h=await Et(u,a??".",t.restrictCwd?[u]:[]);if(!(await d(h)))throw wt(`cwd does not exist: ${h}`);const f=function(t){if(null==t)return[];if(!n.isObject(t))throw wt("`env` must be an object of string=>string");const e=[];for(const[r,i]of Object.entries(t)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw wt(`invalid env key \`${r}\` (must match [A-Za-z_][A-Za-z0-9_]*)`);if("string"==typeof i)e.push([r,i]);else if("number"==typeof i||"boolean"==typeof i)e.push([r,String(i)]);else{if(null!==i)throw wt(`env value for \`${r}\` must be string/number/bool, got ${n.canonicalJson(i)}`);e.push([r,""])}}return e}(e.env),m=fe(e.timeout_ms,"timeout_ms");if(0===m&&0!==t.maxTimeoutMs)throw wt("`timeout_ms` must be a positive integer");const p=(e=>{const n=e??t.timeoutMs;return 0===t.maxTimeoutMs?n:Math.min(Math.max(n,1),t.maxTimeoutMs)})(m);fe(e.wait_ms,"wait_ms");const w=new Map(f);let g=(w.get("PATH")??o().env.get("PATH")??"").trim();for(const t of ee)y=t,g=(_=g)?_.split(":").includes(y)?_:`${_}:${y}`:y;var y,_;w.set("PATH",g),i.call_id&&w.set("XLLM_CALL_ID",i.call_id),i.run_id&&w.set("XLLM_RUN_ID",i.run_id);const v={...t.env,...Object.fromEntries(w)};v.PATH=[...new Set(g.split(":").filter(Boolean))].join(":");const b=re(i.run_dir,i.call_id),$=void 0===b,k=b??l(o().env.get("TMPDIR")||"/tmp",`llm-shell-${o().pid}-${++me}`);try{await o().mkdir(k,{recursive:!0,mode:448})}catch(R){throw gt(`execution directory: ${c(R)}`)}for(const t of["exit","exit.tmp"])await o().remove(l(k,t)).catch((()=>{}));let x;const E=performance.now();try{x=new(o().Command)("/bin/bash",{args:["-c",te,s,k],cwd:h,env:v,stdin:"null",stdout:"null",stderr:"null"}).spawn()}catch(R){throw gt(`spawn shell failed: ${c(R)}`)}const O=async()=>{$&&await o().remove(k,{recursive:!0}).catch((()=>{}))},I=async()=>{try{x.kill("SIGKILL")}catch{}const t=pe(5e3);await Promise.race([x.status,t.done]),t.stop();const e=await le(k,124,!0,performance.now()-E,dt,h,!$);return await O(),e},S=pe(0===p?31536e6:p),T=await Promise.race([x.status.then((t=>({exited:t}))),S.done.then((()=>({timeout:!0}))),i.call.cancelled().then((t=>({cancel:t})))]);let A;if(S.stop(),"exited"in T)A=await le(k,(P=T.exited,P.signal?128+(ue[P.signal]??0):P.code),!1,performance.now()-E,dt,h,!$),await O();else{if(!("timeout"in T)){const t=(await ae(l(k,"stdout"),ht)).trimEnd(),e=await I();throw new pt("cancelled",`shell (native): \`${s}\` was stopped after ${e.duration_ms}ms because ${L=T.cancel,"finishing"===L?"the run is finishing":"deadline"===L?"the run's total time limit was reached":"the run was interrupted"}. It may have had partial side effects; check before repeating it.${t.trim()?`\n--- output so far (tail) ---\n${t}`:""}`)}A=await I()}var L,P;return function(t,e,r,i){if(!e.timed_out){const r=function(t,e){var r;if(function(t){let e=!1,n=!1,r=!1;for(const i of t)if(r)r=!1;else if("\\"!==i||e)if("'"!==i||n)if('"'!==i||e){if("|;&><\n\r".includes(i)&&!e&&!n)return!0}else n=!n;else e=!e;else r=!0;return!1}(t)||!(null==(r=yt(t))?void 0:r.length))return;const i=e.stdout.trim();if(!i)return;let o;try{o=JSON.parse(i)}catch{return}if(!n.isObject(o)||"1"!==o.agent_tool_protocol)return;const s=o.status??"success";if("success"!==s&&"error"!==s&&"pending"!==s)return;for(const n of de)if(void 0!==o[n]&&null!==o[n]&&"string"!=typeof o[n])return;if("pending"===s&&"string"!=typeof o.task_id)return;const a={...o,status:s,summary:"string"==typeof o.summary?o.summary:"",detail:void 0===o.detail?{}:o.detail};return void 0===a.return_code&&0!==e.exit_code&&(a.return_code=e.exit_code),a}(t,e);if(r)return r}const o=e.timed_out?`timed out after ${e.duration_ms}ms (timeout_ms=${r}); the command was stopped. Retry with a larger timeout_ms${0===i?"":` (max ${i})`}, or start a long-lived service with nohup / setsid and return at once.`:`exit=${e.exit_code} in ${e.duration_ms}ms`,s={command:t,cwd:e.cwd,exit_code:e.exit_code,stdout:e.stdout,stderr:e.stderr,output:e.output,output_truncated:e.output_truncated,timed_out:e.timed_out,duration_ms:e.duration_ms,engine:ft,runtime:"native"},a=vt(lt,s,`${lt} ${t}`,o);return a.status=0!==e.exit_code||e.timed_out?"error":"success",a.return_code=e.exit_code,a.title=_t(a),bt(a,e.output)}(s,A,p,t.maxTimeoutMs)}}}const ge="native",ye='set -e\ncommand -v bash >/dev/null\nmachine_id="$(cat /etc/machine-id 2>/dev/null || true)"\n[ -n "$machine_id" ] || machine_id="$(hostname)"\nprintf \'%s\\0\' "$machine_id" "$(hostname)" "$(id -u)" "$(uname -s | tr \'[:upper:]\' \'[:lower:]\')" "$(uname -m)" "$(command -v bash)" "$(pwd -P)" "${PATH}" "$(date +%Y-%m-%dT%H:%M:%S%z)" "$(date +%Z%z)"\nfor tool in bash realpath base64; do if command -v "$tool" >/dev/null; then printf \'%s\\0\' "$tool"; fi; done\n';function _e(t){let e=(new TextDecoder).decode(t);e.endsWith("\0")&&(e=e.slice(0,-1));const r=e.split("\0");if(r.length<10||r.slice(0,10).some((t=>""===t)))throw n.XllmError.capability("execution environment probe returned incomplete data");return{machine:r[0],hostname:r[1],uid:r[2],os:r[3],arch:r[4],shell:r[5],cwd:r[6],path:r[7],current_time:r[8],timezone:r[9],tools:r.slice(10,42)}}async function ve(t,e){if("windows"===o().build.os)throw n.XllmError.capability("the Deno host's native runtime needs bash (Linux / macOS); Windows PowerShell runtimes are Rust-only");let r;try{r=await new(o().Command)("/bin/bash",{args:["-c",ye],cwd:t,env:e,stdin:"null",stdout:"piped",stderr:"piped",signal:AbortSignal.timeout(1e4)}).output()}catch(i){throw n.XllmError.capability(c(i))}if(!r.success)throw n.XllmError.capability(`native capability probe failed: ${(new TextDecoder).decode(r.stderr)}`);return _e(r.stdout)}function be(t){return n.XllmError.config(".llm_context","runtime",t)}function $e(t){for(const[e,n]of Object.entries(t))if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)||n.includes("\0"))throw be(`invalid env key or value \`${e}\``)}const ke="intent";class xe{constructor(t,e,n){this.tools=t,this.workdir=e,this.advertised=n,this.binding={run_id:""},this.ledger=new r.MemoryHintLedger,this.written=[]}bindRun(t){this.binding={...t}}setRecovering(t,e){this.recovering={callId:t,reason:e}}artifacts(){return[...this.written]}has(t){return this.tools.has(t)}hintLedger(){return this.ledger}clearDedup(){this.ledger.clear(r.HINT_NS_DEDUP)}taskResolver(){}listToolSpecs(){return(this.advertised?[...this.advertised.values()]:[...this.tools.values()].map((t=>t.spec))).sort(((t,e)=>t.name<e.name?-1:t.name>e.name?1:0)).map((t=>ut.includes(t.name)?function(t){const e=n.cloneJson(t);let r=e.args_schema;return("object"!=typeof r||null===r||Array.isArray(r))&&(r=e.args_schema={type:"object"}),("object"!=typeof r.properties||null===r.properties||Array.isArray(r.properties))&&(r.properties={}),r.properties[ke]={type:"string",description:"Optional: why you make this call now and what you expect it to give you, in one short sentence. Shown as the progress of your work."},Array.isArray(r.required)&&(r.required=r.required.filter((t=>t!==ke))),e}(t):n.cloneJson(t)))}names(){return[...this.tools.keys()].sort().join(", ")}async callTool(t,e){var n,i;const o=t.call_id,s=this.tools.get(t.name);if(!s)return{kind:"error",call_id:o,message:`tool \`${t.name}\` is not available in this run (available: ${this.names()})`};const a={...t.args??{}};if(ut.includes(t.name)&&delete a[ke],(null==(n=this.recovering)?void 0:n.callId)===o){const t=this.recovering.reason;if(this.recovering=void 0,!s.idempotent)return{kind:"unresolved",call_id:o,reason:t,effect_unknown:!0}}const u=s.call(a,{call_id:o,run_id:this.binding.run_id,run_dir:this.binding.run_dir,call:e}).then((t=>({ok:t})),(t=>({err:t})));let d;if(s.cancellable)d=await u;else{const n=await Promise.race([u,e.cancelledHard().then((t=>({cancelled:t})))]);if("cancelled"in n)return{kind:"cancelled",call_id:o,reason:`tool \`${t.name}\` was abandoned while running (${h=n.cancelled,"deadline"===h?"Deadline":"finishing"===h?"Finishing":"Interrupted"}); it cannot be cancelled, so its effect is unknown`,effect_unknown:!0};d=n}var h;if("err"in d){const t=d.err;if(t instanceof pt){if("transport"===t.kind)throw new r.ToolDispatchException(t.detail,t.effectUnknown);return"cancelled"===t.kind?{kind:"cancelled",call_id:o,reason:t.detail,effect_unknown:t.effectUnknown}:{kind:"error",call_id:o,message:t.message}}return{kind:"error",call_id:o,message:`execution failed: ${c(t)}`}}const f=d.ok;if("success"===f.status&&(t.name===at||t.name===ct)){const t=a.path;if("string"==typeof t){const e=t.startsWith("/")?t:r.normalizePath(l(this.workdir,t));this.written.includes(e)||this.written.push(e)}}if("pending"===f.status){const e=null==(i=f.task_id)?void 0:i.trim();return e?r.taskStateObservation(o,e,{kind:"unknown",reason:"this runtime has no task backend"},{kind:"tools"}):{kind:"error",call_id:o,message:`tool \`${t.name}\` returned a pending result without a task_id`,host:r.toHost(f)}}return r.fitResultBudget(f),r.envelopeObservation(o,f,r.applyHints(f,this.ledger,o))}}function Ee(t,e,n){return{runtime_id:t,kind:ge,host:e.host,target:e,workdir:n.cwd,capabilities:{tools:Object.fromEntries(n.tools.map((t=>[t,"available"]))),network:!0,os:n.os}}}function Oe(t){return t.wait_ms<t.timeout_ms}async function Ie(t={}){const e=n.cloneJson(t.config??{env:{}});e.env=e.env??{},function(t){const e=t.kind??ge;if(r.PLANNED_RUNTIME_KINDS.includes(e))throw n.XllmError.capability(`runtime \`${e}\` is planned but not implemented`);if("site"===e)throw n.XllmError.capability("runtime `site` is built by a website (createSiteRuntime); the Deno host runs `native`");if("remote_ssh"===e||"remote_node"===e)throw n.XllmError.capability(`runtime \`${e}\` is not available on the Deno host (only \`native\`)`);if(e!==ge)throw be(`unknown runtime kind \`${e}\``);if(t.remote_ssh&&void 0!==t.kind)throw be("remote_ssh connection block requires kind: remote_ssh");if(t.remote_node&&void 0!==t.kind)throw be("remote_node connection block requires kind: remote_node");if(t.remote_ssh||t.remote_node)throw be("connection block does not match runtime kind");if($e(t.env??{}),void 0!==t.id&&!t.id.trim())throw be("id cannot be empty");if(0===t.task_wait_ms)throw be("task_wait_ms must be positive")}(e);const i=e.workdir??t.workdir??o().cwd();let s;try{s=await o().realPath(i)}catch(_){throw n.XllmError.capability(`runtime cwd ${i}: ${c(_)}`)}if(!(await d(s)))throw n.XllmError.capability("runtime workdir must be a directory");const a=await ve(s,e.env),u=et(await tt(),a.uid),h=rt(e.id,ge,u),f=function(t,e,n,r){const i=t.os.toLowerCase(),o=t.shell.split(/[/\\]/).pop()??"";return{id:e,kind:ge,os:t.os,arch:t.arch,hostname:t.hostname,shell:t.shell,cwd:t.cwd,tools:t.tools,current_time:t.current_time,timezone:t.timezone,target:n,platform:"darwin"===i||"macos"===i?"macos":i,shell_kind:o.replace(/\.exe$/,"").replace(/\.EXE$/,"").toLowerCase(),baseline:r??""}}(a,h,u,e.baseline),m={...e,kind:ge,id:h,workdir:f.cwd},p=Ee(h,u,a),w=l(o().env.get("BUCKYOS_ROOT")||"/opt/buckyos","data"),g=(t,e,i,o,s,a)=>{const c=[];for(const l of t){const t=r.describeToolSource(l);if("mcp"===l.kind)throw n.XllmError.capability(`${e}: \`${t}\`: MCP tools are not available on the Deno host`);if("named"===l.kind)throw n.XllmError.capability(`${e}: \`${t}\`: named host tools are not available on the Deno host (only the \`bash\` group)`);if(l.groupname===r.BUILTIN_TOOL_GROUP_BASH_CORE||"executor"===l.groupname)throw n.XllmError.capability(`${e}: \`${t}\` needs a host task CLI / executor that the Deno host does not provide (use \`bash\`)`);if(l.groupname!==r.BUILTIN_TOOL_GROUP_BASH)throw n.XllmError.tools(`unknown builtin tool group \`${l.groupname}\` (available: ${r.BUILTIN_TOOL_GROUP_BASH}, ${r.BUILTIN_TOOL_GROUP_BASH_CORE}, executor)`);if(Oe(i))throw n.XllmError.capability(`${e}: \`shell\` would hand commands still running after runtime.task_wait_ms (${i.wait_ms} ms) to a task backend, which the Deno host does not have; set runtime.task_wait_ms to at least tools.shell.timeout_ms (${i.timeout_ms} ms) so \`shell\` waits for its command`);const u="workspace"===o,d={root:f.cwd,allowedRead:u?[f.cwd]:[],allowedWrite:u?[f.cwd]:[],dfsRoot:w},h=[Kt(d),Zt(d),Qt(d),we({workspace:f.cwd,restrictCwd:u,timeoutMs:i.timeout_ms,maxTimeoutMs:i.max_timeout_ms,env:s})];for(const e of h){if(a.has(e.spec.name))throw n.XllmError.tools(`tool name \`${e.spec.name}\` from ${t} conflicts with an already expanded tool of the same name`);a.set(e.spec.name,e),c.push({name:e.spec.name,description:e.spec.description,args_schema:n.cloneJson(e.spec.args_schema),source:t})}}return c};let y;return{kind:ge,probe:a,descriptor:()=>n.cloneJson(p),config:()=>n.cloneJson(m),async info(){const t=await ve(f.cwd,m.env),e=y?[...new Set([...f.tools,...y])].sort().slice(0,32):f.tools;return{...n.cloneJson(f),tools:e,current_time:t.current_time,timezone:t.timezone}},async open(e,i){$e(e.env);const o={...m.env,...e.env};o.PATH=o.PATH??a.path;const s=t.takeover&&t.takeover.run_id===e.run_id?t.takeover.tools:void 0,c=s?{enabled:s.enabled,filesystem_policy:s.filesystem_policy,tools2actions:s.tools2actions,tools:s.tool_sources,actions:s.action_sources,bash_tools:s.bash_tools,shell:{timeout_ms:s.shell.timeout_ms,max_timeout_ms:s.shell.max_timeout_ms}}:i,l=c.enabled??!1,u=c.filesystem_policy??"workspace",d=c.tools2actions??!1,h=r.shellSettings(c.shell,e.task_wait_ms),p=e.loop_model,w={enabled:l,filesystem_policy:u,tools2actions:d,tool_sources:n.cloneJson(c.tools??[]),action_sources:n.cloneJson(c.actions??[]),native:[],actions:[],bash_tools:n.cloneJson(c.bash_tools??[]),shell:h,exec_enabled:!1,sources:{...e.sources}};if("function_call"===p){if(d)throw n.XllmError.capability("`tools2actions: true` requires `loop_model: behavior`; function_call cannot convert tools into actions");if((c.actions??[]).length>0)throw n.XllmError.capability("`actions` are configured but `loop_model` is function_call; use `loop_model: behavior` or remove `actions`")}const _=new Map;if(l){const t=c.tools??[{kind:"group",groupname:r.BUILTIN_TOOL_GROUP_BASH}];w.tool_sources=n.cloneJson(t);const e=g(t,"tools.tools",h,u,o,_),i=g(w.action_sources,"tools.actions",h,u,o,_);"behavior"===p&&d?w.actions=[...e,...i]:(w.native=e,w.actions=i),w.exec_enabled=_.has(lt)&&[...w.native,...w.actions].some((t=>t.name===lt))}let v;if(s){v=new Map;for(const t of[...s.native,...s.actions])_.has(t.name)&&v.set(t.name,{name:t.name,description:t.description,args_schema:n.cloneJson(t.args_schema)})}return y=[...w.native,...w.actions].map((t=>t.name)),{tools:w,manager:new xe(_,f.cwd,v)}},async describeInterrupted(t,e){if(e.name!==lt)return r.unresolvedReason(e.name);const n=re(t.run_dir,e.call_id);return void 0===n?Ae(e,void 0,"(no execution directory)"):Ae(e,await Se(n),n)}}}async function Se(t){let e;try{const n=(await o().stat(l(t,"command"))).mtime;n&&(e=Math.floor(n.getTime()))}catch{e=void 0}return{exit_code:await ce(t),stdout_tail:await ae(l(t,"stdout"),ht),stderr_tail:await ae(l(t,"stderr"),ht),exists:await d(t),started_at_ms:e}}function Te(t){let e="";return t.stdout_tail.trim()&&(e+=`\n--- stdout (tail) ---\n${t.stdout_tail.trimEnd()}`),t.stderr_tail.trim()&&(e+=`\n--- stderr (tail) ---\n${t.stderr_tail.trimEnd()}`),e}function Ae(t,e,n){const r=function(t){var e;const n=null==(e=t.args)?void 0:e.command;if("string"!=typeof n)return"";const r=n.split(/\s+/).filter(Boolean).join(" "),i=[...r];return i.length>160?`${i.slice(0,160).join("")}…`:r}(t),i=void 0!==(null==e?void 0:e.started_at_ms)?`started ${ie(Math.max(0,Date.now()-e.started_at_ms))} ago (at ${e.started_at_ms} ms since epoch)`:"start time unknown";return void 0!==(null==e?void 0:e.exit_code)?`shell (native): the previous executor exited while \`${r}\` was running (${i}). The command has since ended with exit code ${e.exit_code} (read from ${n}); its result was never returned, so review it before deciding whether to repeat anything.${Te(e)}`:`shell (native): the previous executor exited while \`${r}\` was running (${i}). The command may have partly executed; it usually ended together with the executor, but not necessarily (e.g. after kill -9 it may still be running). Background processes it started are unaffected. Check the actual state before repeating it.${e?Te(e):""}`}const Le="~/.xllm/runs",Pe="~/.xllm/locks";function Re(t,e){return r.resolveConfigPath(t,e,function(){const t=o().env;return t.get("HOME")??t.get("USERPROFILE")}())}function De(t,e){if("disabled"===(null==t?void 0:t.kind))return;return Re("path"===(null==t?void 0:t.kind)?t.path:Le,u(e.startsWith("/")?e:l(o().cwd(),e)))}class Me{constructor(t,e){this.file=t,this.path=e,this.released=!1}static async tryAcquire(t){try{await o().mkdir(u(t),{recursive:!0})}catch(r){throw n.XllmError.storage(`cannot create lock directory ${u(t)}: ${c(r)}`)}let e;try{e=await o().open(t,{read:!0,write:!0,create:!0})}catch(r){throw n.XllmError.storage(`cannot open lock ${t}: ${c(r)}`)}if(!(await e.tryLock(!0)))return e.close(),null;try{await o().writeTextFile(t,`${o().pid}\n`)}catch{}return new Me(e,t)}async release(){if(!this.released){this.released=!0;try{await this.file.unlock()}finally{this.file.close()}}}}async function Xe(t){let e;try{e=await o().open(t,{read:!0,write:!0,create:!0})}catch{return!1}try{return!(await e.tryLock(!0))||(await e.unlock(),!1)}finally{e.close()}}let je=0;function Ne(t){return String(t).padStart(4,"0")}class Ue{constructor(t){this.persistent=!0,this.dir=Re(t,o().cwd())}runsDir(){return this.dir}runDir(t){return l(this.dir,t)}async ensureWritable(){try{await o().mkdir(this.dir,{recursive:!0})}catch(e){throw n.XllmError.storage(`runs directory ${this.dir} cannot be created: ${c(e)}`)}const t=l(this.dir,`.probe-${o().pid}`);try{await o().writeFile(t,new Uint8Array)}catch(e){throw n.XllmError.storage(`runs directory ${this.dir} is not writable: ${c(e)}`)}await o().remove(t).catch((()=>{}))}async createRun(){await this.ensureWritable();for(let e=0;e<8;e++){const e=r.generateRunId(),i=this.runDir(e);try{await o().mkdir(i)}catch(t){if(a(t))continue;throw n.XllmError.storage(`cannot create run directory ${i}: ${c(t)}`)}return await o().mkdir(l(i,"snapshots"),{recursive:!0}),e}throw n.XllmError.storage("cannot allocate a unique run id")}async writeRecord(t){const e=this.runDir(t.run_id),r=l(e,"run.json"),i=l(e,`run.json.tmp-${o().pid}-${je++}`);try{await o().mkdir(e,{recursive:!0}),await h(i,(new TextEncoder).encode(JSON.stringify(t,null,2)))}catch(s){throw n.XllmError.storage(`write ${i}: ${c(s)}`)}try{await o().rename(i,r)}catch(s){throw n.XllmError.storage(`commit ${r}: ${c(s)}`)}try{await f(e)}catch(s){throw n.XllmError.storage(`sync ${e}: ${c(s)}`)}}async readRecord(t){const e=l(this.runDir(t),"run.json");let i,a;try{i=await o().readTextFile(e)}catch(d){if(s(d))throw new n.XllmError({kind:"run_not_found",run_id:t,runs_dir:this.dir});throw n.XllmError.storage(`read ${e}: ${c(d)}`)}try{a=JSON.parse(i)}catch(d){throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:c(d)})}const u=a;if((null==u?void 0:u.version)!==r.RUN_RECORD_VERSION)throw n.XllmError.notResumable(t,"unsupported run record version");if("string"!=typeof u.run_id||"string"!=typeof u.status||"object"!=typeof u.config||"object"!=typeof u.prompt)throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:"run.json unreadable: missing run_id / status / config / prompt"});return a}async listRecords(){const t=[];let e;try{e=o().readDir(this.dir);for await(const n of e)if(n.isDirectory)try{const e=JSON.parse(await o().readTextFile(l(this.dir,n.name,"run.json")));e&&"string"==typeof e.run_id&&t.push(e)}catch{}}catch(r){if(s(r))return t;throw n.XllmError.storage(`read runs directory ${this.dir}: ${c(r)}`)}return t}async putSnapshot(t,e){const r=l(this.runDir(t),"snapshots");try{await o().mkdir(r,{recursive:!0});const n=await this.listSnapshots(t),i=n.length?n[n.length-1]+1:1,s=l(r,`${Ne(i)}.json`),a=l(r,`${Ne(i)}.json.tmp`);return await h(a,(new TextEncoder).encode(JSON.stringify(e))),await o().rename(a,s),await f(r),i}catch(i){if(i instanceof n.XllmError)throw i;throw n.XllmError.storage(`write snapshot of ${t}: ${c(i)}`)}}async getSnapshot(t,e){const r=l(this.runDir(t),"snapshots",`${Ne(e)}.json`);let i;try{i=await o().readTextFile(r)}catch(s){throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:`snapshot ${e} missing at ${r}: ${c(s)}`})}try{return JSON.parse(i)}catch(s){throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:`snapshot ${e} unreadable: ${c(s)}`})}}async listSnapshots(t){const e=l(this.runDir(t),"snapshots"),n=[];try{for await(const t of o().readDir(e)){const e=/^(\d+)\.json$/.exec(t.name);e&&n.push(Number(e[1]))}}catch(r){if(s(r))return[];throw r}return n.sort(((t,e)=>t-e))}lockRun(t){return Me.tryAcquire(l(this.runDir(t),".lock"))}async isRunLive(t){return!!(await d(this.runDir(t)))&&Xe(l(this.runDir(t),".lock"))}async removeRun(t){const e=this.runDir(t);try{await o().remove(e,{recursive:!0})}catch(r){if(!s(r))throw n.XllmError.storage(`remove ${e}: ${c(r)}`)}await f(this.dir).catch((()=>{}))}async importRun(t){const e=t.record.run_id;if(await this.isRunLive(e))throw new n.XllmError({kind:"run_busy",run_id:e});const r=this.runDir(e);await o().mkdir(l(r,"snapshots"),{recursive:!0});for(const[n,i]of t.snapshots){const t=l(r,"snapshots",`${Ne(n)}.json`),e=`${t}.tmp`;await h(e,(new TextEncoder).encode(JSON.stringify(i))),await o().rename(e,t)}await f(l(r,"snapshots")),await this.writeRecord(t.record)}}function Ce(t=Pe){const e=Re(t,o().cwd());return async(t,n)=>{const r=await Me.tryAcquire(ot(e,t));return r&&await o().writeTextFile(r.path,`${n}\n`).catch((()=>{})),r}}function Fe(t){return d(t)}const He="BUCKYOS_APPCLIENT_SESSION_TOKEN";async function Be(t){if("env"===t.kind){const e=o().env.get(t.name);if(void 0===e)throw n.XllmError.capability(`environment variable \`${t.name}\` is not set`);return e}let e,r;try{e=await o().readTextFile(t.path)}catch(s){throw n.XllmError.capability(`cannot re-read credential source ${t.path}:${t.field}: ${c(s)}`)}try{r=JSON.parse(e)}catch(s){throw n.XllmError.capability(`cannot parse credential source ${t.path} (the Deno host reads JSON configuration): ${c(s)}`)}let i=r;for(const o of t.field.split(".")){if(!n.isObject(i)||!(o in i))throw n.XllmError.capability(`credential field \`${t.field}\` no longer exists in ${t.path}`);i=i[o]}if("string"!=typeof i||!i.trim())throw n.XllmError.capability(`credential field \`${t.field}\` in ${t.path} is empty or not a string`);return i}function ze(t){return{async infer(){throw n.providerError({refused:{code:r.REFUSED_CREDENTIALS}},t)}}}async function qe(t){var e,r,s;if("openai"===(t.kind??"buckyos")){const e=t.api_key?await Be(t.api_key):o().env.get("OPENAI_API_KEY");if(!(null==e?void 0:e.trim()))throw n.XllmError.capability("openai provider: no API key; set `provider.api_key`, `provider.api_key_env` or the OPENAI_API_KEY environment variable");return new i.OpenAiLlmClient({baseUrl:t.base_url,apiKey:e,headers:t.headers})}if(void 0!==t.on_behalf_of&&null!==t.on_behalf_of)throw n.XllmError.capability("buckyos provider: `on_behalf_of` (a system service paying for a user) is not available on the Deno host");const a=t.session_token?await Be(t.session_token):null==(e=o().env.get(He))?void 0:e.trim();if(!a)return ze(`buckyos provider: no BuckyOS session on this host (set ${He}), sign in and resume`);const l=(null==(r=o().env.get("BUCKYOS_APP_ID"))?void 0:r.trim())||"buckycli",u=new((await async function(){const t=new URL("./node.mjs",self.location).href;return await import(t)}()).BuckyOSSDK)("node");try{await u.initBuckyOS(l,{zoneHost:(null==(s=o().env.get("BUCKYOS_ZONE_HOST"))?void 0:s.trim())??"",appId:l,defaultProtocol:"https://",runtimeType:"AppClient",sessionToken:a,privateKeySearchPaths:[],autoRenew:!1})}catch(d){throw n.XllmError.capability(`buckyos provider: cannot initialize the BuckyOS runtime (check zone/session setup): ${c(d)}`)}return new n.AiccLlmClient(u.getAiccClient())}function We(t,e,n,r={}){const i={llm:n,runtime:t,store:e,pid:o().pid,lockWorkdir:Ce(r.lockDir),workdirExists:Fe};return r.observer&&(i.observer=r.observer),r.tokenizer&&(i.tokenizer=r.tokenizer),i}const Je={infer(){throw n.XllmError.other("the model client is created after the task is prepared")}};function Ge(t){const e=t instanceof n.XllmError?t:n.XllmError.capability(t instanceof Error?t.message:String(t)),r=()=>{throw e},i=()=>Promise.reject(e);return{descriptor:r,config:r,info:i,open:i,describeInterrupted:i}}exports.BASH_GROUP_TOOLS=ut,exports.DEFAULT_LOCK_DIR=Pe,exports.DEFAULT_RUNS_DIR=Le,exports.EDIT_FILE_SPEC=Wt,exports.EXEC_MAX_OUTPUT_BYTES=dt,exports.FileLock=Me,exports.FileRunStore=Ue,exports.HOST_ID_ENV=K,exports.LOCAL_PROBE=ye,exports.NATIVE_KIND=ge,exports.NATIVE_WRAPPER=te,exports.NativeToolManager=xe,exports.READ_FILE_SPEC=zt,exports.SESSION_TOKEN_ENV=He,exports.WRITE_FILE_SPEC=qt,exports.blake3Hex=Y,exports.createLlmClient=qe,exports.createNativeRuntime=Ie,exports.credentialsRefusedClient=ze,exports.deriveRuntimeId=rt,exports.execDirFor=re,exports.fmtElapsed=ie,exports.interruptedShellText=Ae,exports.isLocked=Xe,exports.localProbe=ve,exports.nativeDeps=We,exports.nativeDescriptor=Ee,exports.nativeHostId=tt,exports.nativeHostIdFrom=Q,exports.nativeTarget=et,exports.parseProbe=_e,exports.prepareNativeTask=async function(t,e,n,i,o={}){const s=r.mergeConfigLayers([{path:e,file:r.parseLlmContextJson(e,t??null)}]),a=await Ie({config:s.runtime,workdir:o.workdir});let c=o.store;if(!c){const t=De(s.runs_dir,e);c=void 0===t?new r.MemoryRunStore:new Ue(t)}const l=We(a,c,o.llm??Je,o),u=await r.XllmTask.prepare(t,e,n,i,l);return{task:u,deps:{...l,llm:o.llm??await qe(u.config.provider)}}},exports.readExecDir=Se,exports.resolveHostPath=Re,exports.resolveSecret=Be,exports.resumeNativeRun=async function(t,e,i={},o={}){const s=await t.readRecord(e);let a,c=o.llm;if(r.isTerminal(s.status))a=Ge(n.XllmError.other("a terminal run is not executed"));else{try{a=await Ie({config:s.config.runtime,workdir:s.workdir,takeover:{run_id:s.run_id,tools:s.config.tools}})}catch(l){a=Ge(l)}c=c??await qe(s.config.provider)}return r.XllmRun.resume(t,e,i,We(a,t,c??Je,o))},exports.runsDirOf=De,exports.runtimeIdOf=it,exports.sanitizeCallId=ne,exports.shellSpec=he,exports.targetText=nt,exports.workdirExists=Fe,exports.workdirLockPath=ot,exports.workdirLocker=Ce;
|
|
1
|
+
"use strict";var t=Object.defineProperty,e=(e,n,r)=>(((e,n,r)=>{n in e?t(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r})(e,"symbol"!=typeof n?n+"":n,r),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./aicc-342f2659.js"),r=require("./site_manager-ca22ffbd.js"),i=require("./openai-7aa4ffbf.js");function o(){const t=globalThis.Deno;if(!t)throw new Error("the xllm Deno host needs the Deno runtime");return t}function s(t){return t instanceof o().errors.NotFound}function a(t){return t instanceof o().errors.AlreadyExists}function c(t){return t instanceof Error?t.message:String(t)}function l(...t){let e="";for(const n of t)n&&(e=n.startsWith("/")||!e?n:e.endsWith("/")?e+n:`${e}/${n}`);return e}function u(t){const e=t.replace(/\/+$/,""),n=e.lastIndexOf("/");return n<0?".":0===n?"/":e.slice(0,n)}async function d(t){try{return(await o().stat(t)).isDirectory}catch{return!1}}async function h(t,e){const n=await o().open(t,{write:!0,create:!0,truncate:!0});try{let t=0;for(;t<e.length;)t+=await n.write(e.subarray(t));await n.sync()}finally{n.close()}}async function f(t){if("windows"===o().build.os)return;const e=await o().open(t,{read:!0});try{await e.sync()}finally{e.close()}}require("./krpc_client-26c2dc8b.js");const m=t=>t/2**32|0,p=t=>t>>>0;function w(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name&&"BYTES_PER_ELEMENT"in t&&1===t.BYTES_PER_ELEMENT}const g=t=>t?`"${t}" `:"";function y(t,e=""){if("number"!=typeof t)throw new TypeError(g(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(g(e)+"expected integer >= 0, got "+t);return t}function _(t,e,n=""){if(w(t)&&(void 0===e||t.length===e))return t;void 0!==e&&y(e,"length");const r=w(t),i=void 0!==e?` of length ${e}`:"",o=r?`length=${t.length}`:"type="+typeof t,s=g(n)+"expected Uint8Array"+i+", got "+o;if(!r)throw new TypeError(s);throw new RangeError(s)}const v=(t,e)=>{((t,e)=>{if(null===t||"object"!=typeof t||Array.isArray(t))throw new TypeError(("object"===e?"":`"${e}" `)+"expected object, got type="+typeof t)})(t,e);const n=Object.getPrototypeOf(t);if(n!==Object.prototype&&null!==n)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function b(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function $(t,e){_(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function k(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function x(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function E(t,e){return t<<32-e|t>>>e}const O=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function I(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const S=O?t=>t:t=>I(t)>>>0;const T=O?t=>t:function(t){for(let e=0;e<t.length;e++)t[e]=I(t[e]);return t},A=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),L=Array.from({length:256},((t,e)=>e.toString(16).padStart(2,"0")));function P(t,e,n="opts"){v(t,"defaults"),void 0!==e&&v(e,n);return Object.assign(Object.create(null),t,e)}function R(t,e={}){if("function"!=typeof t)throw new TypeError('"hashCons" expected function, got type='+typeof t);e=P({},e,"info");const n=(e,n)=>t(n).update(e).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=e=>t(e),Object.assign(n,e),Object.freeze(n)}const D=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);function M(t,e,n,r,i){return r=E(r^(t=t+e+i|0),16),{a:t,b:e=E(e^(n=n+r|0),12),c:n,d:r}}function X(t,e,n,r,i){return r=E(r^(t=t+e+i|0),8),{a:t,b:e=E(e^(n=n+r|0),7),c:n,d:r}}class j{constructor(t,n){e(this,"buffer"),e(this,"buffer32"),e(this,"finished",!1),e(this,"destroyed",!1),e(this,"length",0),e(this,"pos",0),e(this,"blockLen"),e(this,"outputLen"),e(this,"canXOF",!1),y(t),y(n),this.blockLen=t,this.outputLen=n,this.buffer=new Uint8Array(t),this.buffer32=k(this.buffer)}update(t){b(this),_(t);const{blockLen:e,buffer:n,buffer32:r}=this,i=t.length,o=t.byteOffset,s=t.buffer;for(let a=0;a<i;){this.pos===e&&(T(r),this.compress(r,0,!1),T(r),this.pos=0);const c=Math.min(e-this.pos,i-a),l=o+a;if(c!==e||l%4||!(a+c<i))n.set(0===a&&c===i?t:t.subarray(a,a+c),this.pos),this.pos+=c,this.length+=c,a+=c;else{const t=new Uint32Array(s,l,Math.floor((i-a)/4));T(t);for(let n=0;a+e<i;n+=r.length,a+=e)this.length+=e,this.compress(t,n,!1);T(t)}}return this}digestInto(t){if(b(this),$(t,this),3&t.byteOffset)throw new RangeError('"output" expected 4-byte aligned byteOffset, got '+t.byteOffset);const{pos:e,buffer32:n}=this;this.finished=!0,this.buffer.fill(0,e),T(n),this.compress(n,0,!0),T(n);const r=this.get(),i=t===this.buffer?n:k(t),o=Math.floor(this.outputLen/4);for(let l=0;l<o;l++)i[l]=S(r[l]);const s=this.outputLen%4;if(!s)return;const a=4*o,c=r[o];for(let l=0;l<s;l++)t[a+l]=c>>>8*l}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){const{buffer:e,length:n,finished:r,destroyed:i,outputLen:o,pos:s}=this;return t||(t=new this.constructor({dkLen:o})),t.set(...this.get()),t.buffer.set(e),t.destroyed=i,t.finished=r,t.length=n,t.pos=s,t.outputLen=o,t}clone(){return this._cloneInto()}}function N(t,e,n,r,i,o,s,a,c,l,u,d,h,f,m,p,w,g,y,_){let v=0;for(let b=0;b<r;b++)({a:i,b:c,c:h,d:w}=M(i,c,h,w,n[e+t[v++]])),({a:i,b:c,c:h,d:w}=X(i,c,h,w,n[e+t[v++]])),({a:o,b:l,c:f,d:g}=M(o,l,f,g,n[e+t[v++]])),({a:o,b:l,c:f,d:g}=X(o,l,f,g,n[e+t[v++]])),({a:s,b:u,c:m,d:y}=M(s,u,m,y,n[e+t[v++]])),({a:s,b:u,c:m,d:y}=X(s,u,m,y,n[e+t[v++]])),({a:a,b:d,c:p,d:_}=M(a,d,p,_,n[e+t[v++]])),({a:a,b:d,c:p,d:_}=X(a,d,p,_,n[e+t[v++]])),({a:i,b:l,c:m,d:_}=M(i,l,m,_,n[e+t[v++]])),({a:i,b:l,c:m,d:_}=X(i,l,m,_,n[e+t[v++]])),({a:o,b:u,c:p,d:w}=M(o,u,p,w,n[e+t[v++]])),({a:o,b:u,c:p,d:w}=X(o,u,p,w,n[e+t[v++]])),({a:s,b:d,c:h,d:g}=M(s,d,h,g,n[e+t[v++]])),({a:s,b:d,c:h,d:g}=X(s,d,h,g,n[e+t[v++]])),({a:a,b:c,c:f,d:y}=M(a,c,f,y,n[e+t[v++]])),({a:a,b:c,c:f,d:y}=X(a,c,f,y,n[e+t[v++]]));return{v0:i,v1:o,v2:s,v3:a,v4:c,v5:l,v6:u,v7:d,v8:h,v9:f,v10:m,v11:p,v12:w,v13:g,v14:y,v15:_}}const U=1,C=2,F=4,H=8,B=16,z=32,q=64,W=D.slice(),J=(()=>{const t=Array.from({length:16},((t,e)=>e)),e=t=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((e=>t[e])),n=[];for(let r=0,i=t;r<7;r++,i=e(i))n.push(...i);return Uint8Array.from(n)})();class G extends j{constructor(t={},n=0){super(64,void 0===(t=P({},t)).dkLen?32:t.dkLen),e(this,"canXOF",!0),e(this,"chunkPos",0),e(this,"chunksDone",0),e(this,"flags",0),e(this,"IV"),e(this,"state"),e(this,"stack",[]),e(this,"posOut",0),e(this,"bufferOut32",new Uint32Array(16)),e(this,"bufferOut"),e(this,"chunkOut",0),e(this,"enableXOF",!0);const{key:r,context:i}=t,o=void 0!==i;if(void 0!==r){if(o)throw new Error('cannot use both "key" and "context"');_(r,32,"key");const t=(s=r,Uint8Array.from(_(s)));this.IV=k(t),T(this.IV),this.flags=n|B}else if(o){_(i,void 0,"context");const t=i,e=new G({dkLen:32},z).update(t).digest();this.IV=k(e),T(this.IV),this.flags=n|q}else this.IV=W,this.flags=n;var s,a;this.state=this.IV.slice(),this.bufferOut=(a=this.bufferOut32,new Uint8Array(a.buffer,a.byteOffset,a.byteLength))}get(){return[]}set(){}b2Compress(t,e,n,r=0){const{state:i,pos:o}=this,s=p(t),a=m(t),{v0:c,v1:l,v2:u,v3:d,v4:h,v5:f,v6:w,v7:g,v8:y,v9:_,v10:v,v11:b,v12:$,v13:k,v14:x,v15:E}=N(J,r,n,7,i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7],W[0],W[1],W[2],W[3],s,a,o,e);i[0]=c^y,i[1]=l^_,i[2]=u^v,i[3]=d^b,i[4]=h^$,i[5]=f^k,i[6]=w^x,i[7]=g^E}compress(t,e=0,n=!1){let r=this.flags;if(this.chunkPos||(r|=U),(15===this.chunkPos||n)&&(r|=C),n||(this.pos=this.blockLen),this.b2Compress(this.chunksDone,r,t,e),this.chunkPos+=1,16===this.chunkPos||n){let t=this.state;this.state=this.IV.slice();for(let e,r=this.chunksDone+1;(n||!(1&r))&&(e=this.stack.pop());r=Math.floor(r/2))this.buffer32.set(e,0),this.buffer32.set(t,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|F,this.buffer32,0),t=this.state,this.state=this.IV.slice();this.chunksDone++,this.chunkPos=0,this.stack.push(t)}this.pos=0}_cloneInto(t){const e=!!t&&t.finished&&!t.destroyed;t=super._cloneInto(t);const{IV:n,flags:r,state:i,chunkPos:o,posOut:s,chunkOut:a,stack:c,chunksDone:l}=this;return t.state.set(i),t.stack=c.map((t=>Uint32Array.from(t))),n===W?(t.IV!==W&&x(t.IV),t.IV=W):t.IV===W?t.IV=n.slice():t.IV.set(n),t.flags=r,t.chunkPos=o,t.chunksDone=l,t.posOut=s,t.chunkOut=a,t.enableXOF=this.enableXOF,this.finished?t.bufferOut32.set(this.bufferOut32):e&&x(t.bufferOut32),t}destroy(){this.destroyed=!0,x(this.state,this.buffer32,this.bufferOut32),this.IV!==W&&x(this.IV),x(...this.stack)}b2CompressOut(){const{state:t,pos:e,flags:n,buffer32:r,bufferOut32:i}=this,o=this.chunkOut++,s=p(o),a=m(o);T(r);const{v0:c,v1:l,v2:u,v3:d,v4:h,v5:f,v6:w,v7:g,v8:y,v9:_,v10:v,v11:b,v12:$,v13:k,v14:x,v15:E}=N(J,0,r,7,t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],W[0],W[1],W[2],W[3],s,a,e,n);i[0]=c^y,i[1]=l^_,i[2]=u^v,i[3]=d^b,i[4]=h^$,i[5]=f^k,i[6]=w^x,i[7]=g^E,i[8]=t[0]^y,i[9]=t[1]^_,i[10]=t[2]^v,i[11]=t[3]^b,i[12]=t[4]^$,i[13]=t[5]^k,i[14]=t[6]^x,i[15]=t[7]^E,T(r),T(i),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,this.buffer.fill(0,this.pos);let t=this.flags|H;this.stack.length?(t|=F,T(this.buffer32),this.compress(this.buffer32,0,!0),T(this.buffer32),this.chunksDone=0,this.pos=this.blockLen):t|=(this.chunkPos?0:U)|C,this.flags=t,this.b2CompressOut()}writeInto(t){b(this,!1),_(t),this.finish();const{blockLen:e,bufferOut:n}=this;for(let r=0,i=t.length;r<i;){this.posOut>=e&&this.b2CompressOut();const o=Math.min(e-this.posOut,i-r);t.set(n.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return t}xofInto(t){if(!this.enableXOF)throw new Error("no XOF after digest()");return this.writeInto(t)}xof(t){return y(t),this.xofInto(new Uint8Array(t))}digestInto(t){if($(t,this),this.finished)throw new Error("digest() was already called");this.enableXOF=!1,this.writeInto(t.length===this.outputLen?t:t.subarray(0,this.outputLen)),this.destroy()}digest(){const t=new Uint8Array(this.outputLen);return this.digestInto(t),t}}const V=R(((t={})=>new G(t))),K="AGENT_TOOL_HOST_ID";function Y(t){return function(t){if(_(t),A)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=L[t[n]];return e}(V((new TextEncoder).encode(t)))}async function Z(t){try{return await o().readTextFile(t)}catch{return null}}function Q(t){var e;const n=null==(e=t.agent_tool_host_id)?void 0:e.trim();if(n)return`host:${n}:`;return`host:${(t.etc_hostname??t.hostname_env??"unknown").trim()}:${(t.machine_id??"").trim()}`}async function tt(){const t=o().env.get(K)??null;return(null==t?void 0:t.trim())?Q({agent_tool_host_id:t,etc_hostname:null,hostname_env:null,machine_id:null}):Q({agent_tool_host_id:t,etc_hostname:await Z("/etc/hostname"),hostname_env:o().env.get("HOSTNAME")??null,machine_id:await Z("/etc/machine-id")})}function et(t,e){return{host:t,uid:e}}function nt(t){return n.canonicalJson(t)}function rt(t,e,n){return t??it(e,n)}function it(t,e){return`${t}:${Y(nt(e)).slice(0,24)}`}function ot(t,e){return l(t,`${Y(e).slice(0,24)}.lock`)}const st="read_file",at="write_file",ct="edit_file",lt="shell",ut=[st,at,ct,lt],dt=61440,ht=2048,ft="native",mt=4*r.RESULT_BUDGET_TOKENS-2048;class pt extends Error{constructor(t,e,n=!1){super("invalid_args"===t?`invalid args: ${e}`:"exec_failed"===t?`execution failed: ${e}`:"timeout"===t?"timeout":"transport"===t?`runtime transport: ${e}`:`cancelled: ${e}`),this.kind=t,this.detail=e,this.effectUnknown=n,this.name="NativeToolError"}}const wt=t=>new pt("invalid_args",t),gt=t=>new pt("exec_failed",t);function yt(t){const e=[];let n="",r=!1,i=!1;const o=[...t];for(let s=0;s<o.length;s++){const t=o[s];"'"!==t||i?'"'!==t||r?"\\"!==t||r?!/\s/.test(t)||r||i?n+=t:n&&(e.push(n),n=""):s+1<o.length&&(n+=o[++s]):i=!i:r=!r}if(!r&&!i)return n&&e.push(n),e}function _t(t){var e;const n=void 0!==t.cmd_name?(null==(e=t.cmd_args)?void 0:e.trim())?`${t.cmd_name} ${t.cmd_args.trim()}`:t.cmd_name:void 0;return`${(void 0!==n?function(t,e){const n=[...t];return n.length<=e?t:`${n.slice(0,e).join("")}...[TRUNCATED]`}(n.trim(),96):"")||"action"} => ${"pending"===t.status?void 0!==t.pending_reason?`pending (${t.pending_reason})`:"pending":t.status}`}function vt(t,e,n,r){const i={agent_tool_protocol:"1",tool:t,status:"success",summary:r,detail:e},o=yt(n),s=o&&o.length?o:n.split(/\s+/).filter(Boolean);return s.length&&(i.cmd_name=s[0],s.length>1&&(i.cmd_args=s.slice(1).join(" "))),i.title=_t(i),i}function bt(t,e){return e.trim()?t.output=e:delete t.output,t}function $t(t,e){return"/"===e?t.startsWith("/"):t===e||t.startsWith(`${e}/`)}function kt(t,e){if(0!==e.length&&!e.some((e=>$t(t,e))))throw wt(`path not allowed by policy: ${t}`)}async function xt(t){let e=t.replace(/\/+$/,"")||"/";const n=[];for(;;)try{const t=await o().realPath(e);return r.normalizePath(l(t,...n.slice().reverse()))}catch(i){if(!s(i))throw gt(c(i));try{throw await o().lstat(e),wt(`dangling symlink: ${e}`)}catch(a){if(a instanceof pt)throw a}const r=e.slice(e.lastIndexOf("/")+1);if(!r||".."===r)throw wt(`cannot resolve ${t}`);"."!==r&&n.push(r);const l=u(e);if(l===e||"/"===e)throw wt("path has no existing ancestor");e=l}}async function Et(t,e,n){if(!e.trim())throw wt("path cannot be empty");const i=e.startsWith("/")?e:l(t,e);kt(r.normalizePath(i),n);const o=await xt(i);return kt(o,await Promise.all(n.map(xt))),o}function Ot(t){let e="";for(const n of(new TextEncoder).encode(t)){const t=String.fromCharCode(n);e+=/[A-Za-z0-9\-._~!$&'()*+,;=:@]/.test(t)?t:`%${n.toString(16).toUpperCase().padStart(2,"0")}`}return e}function It(t,e){if(!t)return;const n=r.normalizePath(t);if(!$t(e,n))return;return`cyfs://${["",...e.slice(n.length).split("/").filter((t=>t&&"."!==t))].map(Ot).join("/")||"/"}`}function St(t){return null===t?"null":"boolean"==typeof t?`boolean \`${t}\``:"number"==typeof t?Number.isInteger(t)?`integer \`${t}\``:`floating point \`${t}\``:"string"==typeof t?`string ${JSON.stringify(t)}`:Array.isArray(t)?"sequence":"map"}function Tt(t,e){return wt(`invalid args for \`${t}\`: ${e}`)}function At(t,e,n){const r=e[n];if(void 0===r)throw Tt(t,`missing field \`${n}\``);if("string"!=typeof r)throw Tt(t,`invalid type: ${St(r)}, expected a string`);return r}function Lt(t,e,n){const r=e[n];if(null!=r){if("string"!=typeof r)throw Tt(t,`invalid type: ${St(r)}, expected a string`);return r}}const Pt=new TextEncoder;function Rt(t){return Pt.encode(t).length}function Dt(t){return new TextDecoder("utf-8",{ignoreBOM:!0}).decode(t)}function Mt(t){return t?t.match(/[^\n]*\n|[^\n]+$/g)??[]:[]}function Xt(t){if(!t)return[];const e=t.split("\n");return""===e[e.length-1]&&e.pop(),e.map((t=>t.endsWith("\r")?t.slice(0,-1):t))}function jt(t){return t.replace(/[\r\n]+$/,"")}function Nt(t){const e=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\r/g,"\\r").replace(/\n/g,"\\n"),n=t?Math.max(Xt(t).length,1):0,r=[...e];return r.length<=64?e:`${r.slice(0,32).join("")}...(total ${n} lines)...${r.slice(-32).join("")}`}function Ut(t,e){const n=t.trim();if("$"===n)return"end";if(n.startsWith("+")||!/^-?\d+$/.test(n))throw wt(`invalid range text \`${e}\``);const r=Number(n);if(0===r)throw wt("range must be 1-based, zero is invalid");return r}function Ct(t,e){const n=t.trim();if(!n.startsWith("+"))throw wt(`invalid range text \`${e}\``);const r=n.slice(1).trim();if(!/^\d+$/.test(r))throw wt(`invalid range text \`${e}\``);const i=Number(r);if(0===i)throw wt("range count must be positive integer");return i}function Ft(t,e){if("string"==typeof t)return Ut(t,e);if("number"==typeof t&&Number.isInteger(t)){if(0===t)throw wt(`${e} must be non-zero integer`);return t}throw wt(`${e} must be integer or \`$\``)}function Ht(t){if(null!=t){if(n.isObject(t)){const e=void 0!==t.start?Ft(t.start,"range.start"):void 0,n=void 0!==t.end?Ft(t.end,"range.end"):void 0,r=void 0!==t.count?function(t,e){if("number"!=typeof t||!Number.isInteger(t)||t<=0)throw wt(`${e} must be positive integer`);return t}(t.count,"range.count"):void 0;if(void 0!==r&&void 0!==n)throw wt("range cannot set both `end` and `count`");if(void 0!==r&&void 0===e)throw wt("range.count requires range.start");if(void 0===e&&void 0===n&&void 0===r)throw wt("range object must contain at least one of start/end/count");return{start:e,end:n,count:r,defaultEnd:"tail_if_start_negative"}}if(Array.isArray(t)){if(0===t.length||t.length>2)throw wt("range array must be [start] or [start,end]");return{start:Ft(t[0],"range[0]"),end:2===t.length?Ft(t[1],"range[1]"):void 0,defaultEnd:"same_as_start"}}if("number"==typeof t&&Number.isInteger(t))return{start:Ft(t,"range"),defaultEnd:"same_as_start"};if("string"==typeof t)return function(t){const e=t.trim();if(!e||"-"===e)return;if(e.includes(",")||e.includes(":")){if(e.includes(",")&&e.includes(":"))throw wt(`invalid range text \`${t}\``);const n=e.split(e.includes(",")?",":":");if(2!==n.length)throw wt(`invalid range text \`${t}\``);const r=n[0].trim()?Ut(n[0].trim(),t):void 0,i=n[1].trim();if(i.startsWith("+")){if(void 0===r)throw wt(`range \`${t}\` with \`+count\` requires start`);return{start:r,count:Ct(i,t),defaultEnd:"same_as_start"}}return{start:r,end:i?Ut(i,t):void 0,defaultEnd:"end"}}const n=e.indexOf("-");if(n>=0){const r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(r&&i&&/^\d+$/.test(r)&&/^\d+$/.test(i))return{start:Ut(r,t),end:Ut(i,t),defaultEnd:"same_as_start"}}return{start:Ut(e,t),defaultEnd:"same_as_start"}}(t);throw wt("range must be string/number/array/object")}}function Bt(t,e){return"end"===t?e:t>0?t:e+t+1}const zt={name:st,description:'Read a text file. range selects 1-based lines ("120-200", "120:$", "120:+20", "-50:$" for the last 50); first_chunk starts the read at the first occurrence of that text. Paths are relative to the working directory; paths outside it only where the run\'s filesystem policy allows.',args_schema:{properties:{first_chunk:{description:"Start the read at the first occurrence of this text (range then counts from there).",type:"string"},path:{description:"File to read, relative to the working directory.",type:"string"},range:{description:'1-based line range: "120-200", "120:$" (to the end), "120:+20" (20 lines from 120); negative numbers count from the end ("-50:$").'}},required:["path"],type:"object"}},qt={name:at,description:'Write a text file: mode "write" (default) creates or overwrites it, "append" adds to its end, "new" creates it and fails if it exists. Parent directories are created. Paths are relative to the working directory; paths outside it only where the run\'s filesystem policy allows.',args_schema:{properties:{content:{description:"The text to write.",type:"string"},mode:{description:"`write` (default): create or overwrite; `append`: add to the end; `new`: create, fail if the file exists.",type:"string"},path:{description:"File to write, relative to the working directory.",type:"string"}},required:["content","path"],type:"object"}},Wt={name:ct,description:"Replace the one exact occurrence of old_string with new_string in a text file. Fails when old_string is absent or occurs more than once: include enough surrounding text to make it unique. Paths are relative to the working directory; paths outside it only where the run's filesystem policy allows.",args_schema:{properties:{new_string:{description:"The replacement text.",type:"string"},old_string:{description:"The exact text to replace; it must occur exactly once.",type:"string"},path:{description:"File to edit, relative to the working directory.",type:"string"}},required:["new_string","old_string","path"],type:"object"}};async function Jt(t){try{return await o().readFile(t)}catch(e){throw gt(`read file failed: ${c(e)}`)}}async function Gt(t){return Dt(await Jt(t))}async function Vt(t,e){try{await o().mkdir(u(t),{recursive:!0})}catch(n){throw gt(c(n))}try{await o().writeFile(t,Pt.encode(e))}catch(n){throw gt(`write file failed: ${c(n)}`)}}function Kt(t){return{spec:zt,idempotent:!0,cancellable:!1,async call(e){const i=At(st,e,"path"),o=Lt(st,e,"first_chunk"),s=null===e.range?void 0:e.range,a=i.trim();if(!a)throw wt("missing required arg `path`");const c=await Et(t.root,a,t.allowedRead),l=await Jt(c);if(function(t){return t.subarray(0,8192).includes(0)}(l))throw wt(`\`${a}\` is a binary file (${l.length} bytes): read_file only reads text. Use llm_understand_media for images, PDFs and office documents, or a shell command that converts or inspects the format.`);const u=Dt(l);let d,h=!0,f=1;if(void 0!==o){const t=u.indexOf(o);t>=0?(d=u.slice(t),f=(u.slice(0,t).match(/\n/g)??[]).length+1):(d="",h=!1)}else d=u;const m=Mt(d),p=m.length,w=Ht(s);let g,y,_="";w?([g,y]=function(t,e){const n=t.start??1,r=Bt(n,e);let i;return i=void 0!==t.count?r+t.count-1:void 0!==t.end?Bt(t.end,e):"same_as_start"===t.defaultEnd?r:"end"===t.defaultEnd||"number"==typeof n&&n<0?e:r,[Math.min(Math.max(r,1),e+1),Math.min(Math.max(i,0),e)]}(w,p),_=`${g}-${y}`):0===p?(g=1,y=0):(g=1,y=p);const v=Math.min(Math.max(g-1,0),p),b=Math.min(y,p),$=v<b?m.slice(v,b):[],k=$.join(""),x=$.length,E=0===x?null:f+v,O=null===E?null:E+Math.max(x-1,0),I=function(t,e,n){const r={text:"",shown:0};if(null===t)return r;let i=0;for(let o=0;o<Math.min(e.length,200);o++){const s=t+o,a=jt(e[o]),c=`${s}: `,l=o>0?1:0,u=Rt(a);if(i+l+c.length+u>n){if(0===o){const t=(new TextEncoder).encode(a);let e=Math.min(Math.max(n-c.length,0),t.length);for(;e>0&&e<t.length&&128==(192&t[e]);)e--;r.text=c+(new TextDecoder).decode(t.subarray(0,e)),r.shown=1,r.cut=[s,e,t.length]}break}l&&(r.text+="\n"),r.text+=c+a,i+=l+c.length+u,r.shown++}return r}(E,$,mt),S=Rt(k),T=function(t,e,r){let i=`${st} ${t}`;if(void 0!==e&&(i+=` first_chunk="${Nt(e)}"`),null!=r){const t="string"==typeof r?r:n.canonicalJson(r);t.trim()&&(i+=` range=${t}`)}return i}(a,o,s),A=Mt(u).length,L=null!==E&&I.shown>0?E+I.shown-1:null,P=()=>{if(null===O||null===E)return;const t=null===L?E:L+1;return t<=O?[t,O]:void 0},R=()=>null!==L&&void 0===P()&&void 0===I.cut&&L<A?L:void 0;let D;if(h)if(null===L)D=`${a}: read 0 lines (the file has ${1===A?"1 line":`${A} lines`})`;else{D=`${a}: shown lines ${E}–${L} of ${A} (${S} bytes read)`,I.cut&&(D+=`; line ${I.cut[0]} cut at ${I.cut[1]} of ${I.cut[2]} bytes`);const t=P();t&&(D+=`; lines ${t[0]}–${t[1]} not shown`)}else D=`first_chunk was not found in ${a}: nothing read`;const M={path:c},X=It(t.dfsRoot,c);void 0!==X&&(M.cyfs_url=X),Object.assign(M,{content:k,matched:h,line_range:_,bytes:S,line_count:x,total_lines:A,start_line:E,end_line:O,preview_truncated:I.shown<x||void 0!==I.cut});const j=vt(st,M,T,D);if(j.title=`${T} => ${h?"success":"anchor not found"}`,I.text){let t=I.text;if(I.cut){const[e,n,r]=I.cut;t+=`\n[line ${e} has ${r} bytes, the first ${n} are shown`,c.startsWith("/")&&(t+=`; read the rest with a command such as \`sed -n '${e}p' ${c} | cut -b ${n+1}-${n+mt}\``),t+="]"}const e=P(),n=void 0!==o?" and without first_chunk (these are lines of the whole file)":"",r=Math.max(I.shown,1);if(e)t+=`\n[lines ${e[0]}–${e[1]} not shown: read again with range=${e[0]}-${Math.min(e[1],e[0]+r-1)}${n}]`;else if(void 0!==R()){const e=R();t+=`\n[shown lines ${E??e}–${e} of ${A}; the next lines: range=${e+1}-${Math.min(A,e+r)}${n}]`}bt(j,t)}return(P()||I.cut||void 0!==R())&&(j.hints=[{text:'`range` reads any part: "201-400", "201:+200" (200 lines from 201), "-50:$" (the last 50). Line numbers are those of the whole text.',once:"read.paging"}]),function(t,e){if("success"!==t.status||!n.isObject(t.detail))return t;const i=t.detail,o="string"==typeof i.path?i.path:e,s=t=>"number"==typeof i[t]?String(i[t]):"";return t.dedup={key:`read:${o}#${s("start_line")}-${s("end_line")}::${Y(r.observationText(t)).slice(0,16)}`,hint:`\`${e}\` is unchanged`},t}(j,a)}}}function Yt(t){const e=(t??"write").trim().toLowerCase();if("new"===e||"create"===e)return"new";if("append"===e)return"append";if(""===e||"write"===e||"overwrite"===e)return"write";throw wt(`invalid write mode \`${e}\`, expected new/append/write`)}function Zt(t){return{spec:qt,idempotent:!1,cancellable:!1,async call(e){const n=At(at,e,"path"),r=At(at,e,"content"),i=Lt(at,e,"mode");let a;try{a=Yt(i)}catch{a="write"}const l=`${at} ${n} mode=${a}`,u=n.trim();if(!u)throw wt("missing required arg `path`");const d=Yt(i),h=await Et(t.root,u,t.allowedWrite),f=await async function(t){try{return await o().stat(t),!0}catch(e){if(s(e))return!1;throw gt(c(e))}}(h);if("new"===d&&f)throw wt(`write mode \`new\` requires target file not exist: ${u}`);const m=f?await Gt(h):"",p="append"===d?"append":"new"===d?"new":f?"write":"create",w="append"===d?`${m}${r}`:r;await Vt(h,w);const g=Mt(r).length,y={},_=It(t.dfsRoot,h);void 0!==_&&(y.cyfs_url=_);const v=Rt(w);Object.assign(y,{created:!f,changed:m!==w,bytes_written:v,line_count:g});const b=`${"append"===p?"appended":"new"===p||"create"===p?"created":"wrote"} ${u}, wrote ${Rt(r)} bytes across ${1===g?"1 line":`${g} lines`}`,$=vt(at,y,l,b),k="append"===p?"append":"new"===p||"create"===p?"new":"write";return $.title=`${at} ${u} mode=${k} => success (${v} bytes)`,$}}}function Qt(t){return{spec:Wt,idempotent:!1,cancellable:!1,async call(e){const n=At(ct,e,"path"),r=At(ct,e,"old_string"),i=At(ct,e,"new_string"),o=`${ct} ${n} old_string="${Nt(r)}"`,s=n.trim();if(!s)throw wt("missing required arg `path`");if(!r)throw wt("missing required arg `old_string`");if(r===i)throw wt("`new_string` must be different from `old_string`");const a=await Et(t.root,s,t.allowedWrite),c=await Gt(a),l=[];for(let t=c.indexOf(r);t>=0;t=c.indexOf(r,t+r.length))l.push(t);if(0===l.length)throw wt("`old_string` was not found in the file");if(l.length>1)throw wt(`\`old_string\` must match exactly once, found ${l.length} matches`);const u=l[0],d=c.slice(0,u)+i+c.slice(u+r.length),h=c!==d;h&&await Vt(a,d);const f=function(t,e,n){const r=Xt(e),i=Xt(n),o=[];for(let s=0;s<Math.max(r.length,i.length);s++){const t=r[s],e=i[s];void 0!==t&&void 0!==e?t===e?o.push(` ${t}`):o.push(`-${t}`,`+${e}`):void 0!==t?o.push(`-${t}`):void 0!==e&&o.push(`+${e}`)}return[`--- a/${t}`,`+++ b/${t}`,`@@ -1,${r.length} +1,${i.length} @@`,...o].join("\n")}(s,c,d),m=(c.slice(0,u).match(/\n/g)??[]).length+1,p={},w=It(t.dfsRoot,a);void 0!==w&&(p.cyfs_url=w),Object.assign(p,{matched:!0,changed:h,mode:"replace",line:m,diff:f,diff_truncated:!1});const g=vt(ct,p,o,h?`edited ${s} with replace at line ${m}`:`edit ${s} made no change`);return h&&f.trim()&&bt(g,f),g.title=`${ct} ${s} => ${h?`success (line ${m})`:"no change"}`,g}}}const te='if [ "$#" -ge 2 ]; then export PATH="$2"; fi\nprintf \'%s\\n\' "$0" > "$1/command"\n"$BASH" -c "$0" </dev/null >"$1/stdout" 2>"$1/stderr"\n__llm_ec=$?\nprintf \'%s\\n\' "$__llm_ec" > "$1/exit.tmp" && command -p mv -f "$1/exit.tmp" "$1/exit"\nexit $__llm_ec',ee=["/usr/local/sbin","/usr/local/bin","/usr/sbin","/usr/bin","/sbin","/bin"];function ne(t){const e=[...t].map((t=>/[A-Za-z0-9\-_.]/.test(t)?t:"_")).join("");return!e||e.startsWith(".")?`c_${e}`:e}function re(t,e){if(t&&e)return l(t,"exec",ne(e))}function ie(t){const e=Math.floor(t/1e3);return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${String(e%60).padStart(2,"0")}s`:`${Math.floor(e/3600)}h${String(Math.floor(e%3600/60)).padStart(2,"0")}m`}function oe(t,e,n){const r=Math.floor(e/4),i=e-r,o=t.subarray(0,Math.min(r,t.length)),s=t.subarray(o.length),a=s.subarray(Math.max(0,s.length-i));if(!(t.length>o.length+a.length))return[Dt(o)+Dt(a),!1];const c=t.length-o.length-a.length,l=void 0===n?`…[${c} bytes omitted]…`:`…[${c} bytes omitted; full ${n.split("/").pop()||"output"}: ${n}]…`;return[`${Dt(o)}\n${l}\n${Dt(a)}`,!0]}async function se(t){try{return await o().readFile(t)}catch{return}}async function ae(t,e){const n=await se(t);return n?Dt(n.subarray(Math.max(0,n.length-e))):""}async function ce(t){try{const e=(await o().readTextFile(l(t,"exit"))).trim();return/^[+-]?\d+$/.test(e)?Number(e):void 0}catch{return}}async function le(t,e,n,r,i,o,s){const a=l(t,"stdout"),c=l(t,"stderr"),u=await se(a)??new Uint8Array,d=await se(c)??new Uint8Array,[h,f]=function(t,e,n){if(t+e<=n)return[t,e];const r=Math.floor(n/2);return t<=r?[t,n-t]:e<=r?[n-e,e]:[r,n-r]}(u.length,d.length,i),[m,p]=oe(u,Math.max(h,16),s?a:void 0),[w,g]=oe(d,Math.max(f,16),s?c:void 0);let y=m;return w&&(y&&!y.endsWith("\n")&&(y+="\n"),y+=w),{exit_code:e,stdout:m,stderr:w,output:y,output_truncated:p||g,timed_out:n,duration_ms:Math.floor(r),cwd:o}}const ue={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGBUS:7,SIGFPE:8,SIGKILL:9,SIGUSR1:10,SIGSEGV:11,SIGUSR2:12,SIGPIPE:13,SIGALRM:14,SIGTERM:15};const de=["tool","cmd_name","task_id","pending_reason","estimated_wait","title","summary","cmd_args","partial_output","output"];function he(t){const e=t.maxTimeoutMs,n=`Run a command in this run's runtime (native) with bash syntax. It starts in the working directory unless cwd is given; it is not sandboxed and runs with the current user's permissions. The command is a child process of this executor: an interrupt or a timeout ends its process group; processes it leaves behind after returning are not managed. Waits for the command to finish. Default timeout ${Math.floor(t.timeoutMs/1e3)}s${0===e?", no upper limit":`, max ${Math.floor(e/1e3)}s`}; on timeout the command is stopped and the output so far is returned. Start a long-lived service with nohup / setsid and return at once; on Unix, processes started with \`&\` / nohup in the foreground command's process group also end when that command is interrupted or times out. Long output keeps its beginning and end.`,r={description:`Timeout in milliseconds (default ${t.timeoutMs}${0===e?"":`, max ${e}`}). Set it explicitly for long builds, tests or media commands.`,minimum:1,type:"integer"};return 0!==e&&(r.maximum=e),{name:lt,description:n,args_schema:{properties:{command:{description:"bash command to execute",type:"string"},cwd:{description:t.restrictCwd?"Working directory, relative to or within the configured workspace. Defaults to the workspace.":"Working directory, absolute or relative to the default working directory. Defaults to that directory; outside paths are allowed subject to OS permissions.",type:"string"},timeout_ms:r},required:["command"],type:"object"}}}function fe(t,e){if(null!=t){if("number"==typeof t&&Number.isInteger(t)&&t>=0)return t;if("string"==typeof t&&/^\d+$/.test(t.trim()))return Number(t.trim());throw wt(`\`${e}\` must be a non-negative integer`)}}let me=0;function pe(t){let e;return{done:new Promise((n=>{e=setTimeout((()=>n("timeout")),Math.min(t,2**31-1))})),stop:()=>clearTimeout(e)}}function we(t){return{spec:he(t),idempotent:!1,cancellable:!0,async call(e,i){const s="string"==typeof e.command?e.command.trim():"";if(!s)throw wt("`command` is required and must be non-empty");const a="string"==typeof e.cwd?e.cwd:void 0,u=r.normalizePath(t.workspace),h=await Et(u,a??".",t.restrictCwd?[u]:[]);if(!(await d(h)))throw wt(`cwd does not exist: ${h}`);const f=function(t){if(null==t)return[];if(!n.isObject(t))throw wt("`env` must be an object of string=>string");const e=[];for(const[r,i]of Object.entries(t)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw wt(`invalid env key \`${r}\` (must match [A-Za-z_][A-Za-z0-9_]*)`);if("string"==typeof i)e.push([r,i]);else if("number"==typeof i||"boolean"==typeof i)e.push([r,String(i)]);else{if(null!==i)throw wt(`env value for \`${r}\` must be string/number/bool, got ${n.canonicalJson(i)}`);e.push([r,""])}}return e}(e.env),m=fe(e.timeout_ms,"timeout_ms");if(0===m&&0!==t.maxTimeoutMs)throw wt("`timeout_ms` must be a positive integer");const p=(e=>{const n=e??t.timeoutMs;return 0===t.maxTimeoutMs?n:Math.min(Math.max(n,1),t.maxTimeoutMs)})(m);fe(e.wait_ms,"wait_ms");const w=new Map(f);let g=(w.get("PATH")??o().env.get("PATH")??"").trim();for(const t of ee)y=t,g=(_=g)?_.split(":").includes(y)?_:`${_}:${y}`:y;var y,_;w.set("PATH",g),i.call_id&&w.set("XLLM_CALL_ID",i.call_id),i.run_id&&w.set("XLLM_RUN_ID",i.run_id);const v={...t.env,...Object.fromEntries(w)};v.PATH=[...new Set(g.split(":").filter(Boolean))].join(":");const b=re(i.run_dir,i.call_id),$=void 0===b,k=b??l(o().env.get("TMPDIR")||"/tmp",`llm-shell-${o().pid}-${++me}`);try{await o().mkdir(k,{recursive:!0,mode:448})}catch(R){throw gt(`execution directory: ${c(R)}`)}for(const t of["exit","exit.tmp"])await o().remove(l(k,t)).catch((()=>{}));let x;const E=performance.now();try{x=new(o().Command)("/bin/bash",{args:["-c",te,s,k],cwd:h,env:v,stdin:"null",stdout:"null",stderr:"null"}).spawn()}catch(R){throw gt(`spawn shell failed: ${c(R)}`)}const O=async()=>{$&&await o().remove(k,{recursive:!0}).catch((()=>{}))},I=async()=>{try{x.kill("SIGKILL")}catch{}const t=pe(5e3);await Promise.race([x.status,t.done]),t.stop();const e=await le(k,124,!0,performance.now()-E,dt,h,!$);return await O(),e},S=pe(0===p?31536e6:p),T=await Promise.race([x.status.then((t=>({exited:t}))),S.done.then((()=>({timeout:!0}))),i.call.cancelled().then((t=>({cancel:t})))]);let A;if(S.stop(),"exited"in T)A=await le(k,(P=T.exited,P.signal?128+(ue[P.signal]??0):P.code),!1,performance.now()-E,dt,h,!$),await O();else{if(!("timeout"in T)){const t=(await ae(l(k,"stdout"),ht)).trimEnd(),e=await I();throw new pt("cancelled",`shell (native): \`${s}\` was stopped after ${e.duration_ms}ms because ${L=T.cancel,"finishing"===L?"the run is finishing":"deadline"===L?"the run's total time limit was reached":"the run was interrupted"}. It may have had partial side effects; check before repeating it.${t.trim()?`\n--- output so far (tail) ---\n${t}`:""}`)}A=await I()}var L,P;return function(t,e,r,i){if(!e.timed_out){const r=function(t,e){var r;if(function(t){let e=!1,n=!1,r=!1;for(const i of t)if(r)r=!1;else if("\\"!==i||e)if("'"!==i||n)if('"'!==i||e){if("|;&><\n\r".includes(i)&&!e&&!n)return!0}else n=!n;else e=!e;else r=!0;return!1}(t)||!(null==(r=yt(t))?void 0:r.length))return;const i=e.stdout.trim();if(!i)return;let o;try{o=JSON.parse(i)}catch{return}if(!n.isObject(o)||"1"!==o.agent_tool_protocol)return;const s=o.status??"success";if("success"!==s&&"error"!==s&&"pending"!==s)return;for(const n of de)if(void 0!==o[n]&&null!==o[n]&&"string"!=typeof o[n])return;if("pending"===s&&"string"!=typeof o.task_id)return;const a={...o,status:s,summary:"string"==typeof o.summary?o.summary:"",detail:void 0===o.detail?{}:o.detail};return void 0===a.return_code&&0!==e.exit_code&&(a.return_code=e.exit_code),a}(t,e);if(r)return r}const o=e.timed_out?`timed out after ${e.duration_ms}ms (timeout_ms=${r}); the command was stopped. Retry with a larger timeout_ms${0===i?"":` (max ${i})`}, or start a long-lived service with nohup / setsid and return at once.`:`exit=${e.exit_code} in ${e.duration_ms}ms`,s={command:t,cwd:e.cwd,exit_code:e.exit_code,stdout:e.stdout,stderr:e.stderr,output:e.output,output_truncated:e.output_truncated,timed_out:e.timed_out,duration_ms:e.duration_ms,engine:ft,runtime:"native"},a=vt(lt,s,`${lt} ${t}`,o);return a.status=0!==e.exit_code||e.timed_out?"error":"success",a.return_code=e.exit_code,a.title=_t(a),bt(a,e.output)}(s,A,p,t.maxTimeoutMs)}}}const ge="native",ye='set -e\ncommand -v bash >/dev/null\nmachine_id="$(cat /etc/machine-id 2>/dev/null || true)"\n[ -n "$machine_id" ] || machine_id="$(hostname)"\nprintf \'%s\\0\' "$machine_id" "$(hostname)" "$(id -u)" "$(uname -s | tr \'[:upper:]\' \'[:lower:]\')" "$(uname -m)" "$(command -v bash)" "$(pwd -P)" "${PATH}" "$(date +%Y-%m-%dT%H:%M:%S%z)" "$(date +%Z%z)"\nfor tool in bash realpath base64; do if command -v "$tool" >/dev/null; then printf \'%s\\0\' "$tool"; fi; done\n';function _e(t){let e=(new TextDecoder).decode(t);e.endsWith("\0")&&(e=e.slice(0,-1));const r=e.split("\0");if(r.length<10||r.slice(0,10).some((t=>""===t)))throw n.XllmError.capability("execution environment probe returned incomplete data");return{machine:r[0],hostname:r[1],uid:r[2],os:r[3],arch:r[4],shell:r[5],cwd:r[6],path:r[7],current_time:r[8],timezone:r[9],tools:r.slice(10,42)}}async function ve(t,e){if("windows"===o().build.os)throw n.XllmError.capability("the Deno host's native runtime needs bash (Linux / macOS); Windows PowerShell runtimes are Rust-only");let r;try{r=await new(o().Command)("/bin/bash",{args:["-c",ye],cwd:t,env:e,stdin:"null",stdout:"piped",stderr:"piped",signal:AbortSignal.timeout(1e4)}).output()}catch(i){throw n.XllmError.capability(c(i))}if(!r.success)throw n.XllmError.capability(`native capability probe failed: ${(new TextDecoder).decode(r.stderr)}`);return _e(r.stdout)}function be(t){return n.XllmError.config(".llm_context","runtime",t)}function $e(t){for(const[e,n]of Object.entries(t))if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)||n.includes("\0"))throw be(`invalid env key or value \`${e}\``)}const ke="intent";class xe{constructor(t,e,n){this.tools=t,this.workdir=e,this.advertised=n,this.binding={run_id:""},this.ledger=new r.MemoryHintLedger,this.written=[]}bindRun(t){this.binding={...t}}setRecovering(t,e){this.recovering={callId:t,reason:e}}artifacts(){return[...this.written]}has(t){return this.tools.has(t)}hintLedger(){return this.ledger}clearDedup(){this.ledger.clear(r.HINT_NS_DEDUP)}taskResolver(){}listToolSpecs(){return(this.advertised?[...this.advertised.values()]:[...this.tools.values()].map((t=>t.spec))).sort(((t,e)=>t.name<e.name?-1:t.name>e.name?1:0)).map((t=>ut.includes(t.name)?function(t){const e=n.cloneJson(t);let r=e.args_schema;return("object"!=typeof r||null===r||Array.isArray(r))&&(r=e.args_schema={type:"object"}),("object"!=typeof r.properties||null===r.properties||Array.isArray(r.properties))&&(r.properties={}),r.properties[ke]={type:"string",description:"Optional: why you make this call now and what you expect it to give you, in one short sentence. Shown as the progress of your work."},Array.isArray(r.required)&&(r.required=r.required.filter((t=>t!==ke))),e}(t):n.cloneJson(t)))}names(){return[...this.tools.keys()].sort().join(", ")}async callTool(t,e){var n,i;const o=t.call_id,s=this.tools.get(t.name);if(!s)return{kind:"error",call_id:o,message:`tool \`${t.name}\` is not available in this run (available: ${this.names()})`};const a={...t.args??{}};if(ut.includes(t.name)&&delete a[ke],(null==(n=this.recovering)?void 0:n.callId)===o){const t=this.recovering.reason;if(this.recovering=void 0,!s.idempotent)return{kind:"unresolved",call_id:o,reason:t,effect_unknown:!0}}const u=s.call(a,{call_id:o,run_id:this.binding.run_id,run_dir:this.binding.run_dir,call:e}).then((t=>({ok:t})),(t=>({err:t})));let d;if(s.cancellable)d=await u;else{const n=await Promise.race([u,e.cancelledHard().then((t=>({cancelled:t})))]);if("cancelled"in n)return{kind:"cancelled",call_id:o,reason:`tool \`${t.name}\` was abandoned while running (${h=n.cancelled,"deadline"===h?"Deadline":"finishing"===h?"Finishing":"Interrupted"}); it cannot be cancelled, so its effect is unknown`,effect_unknown:!0};d=n}var h;if("err"in d){const t=d.err;if(t instanceof pt){if("transport"===t.kind)throw new r.ToolDispatchException(t.detail,t.effectUnknown);return"cancelled"===t.kind?{kind:"cancelled",call_id:o,reason:t.detail,effect_unknown:t.effectUnknown}:{kind:"error",call_id:o,message:t.message}}return{kind:"error",call_id:o,message:`execution failed: ${c(t)}`}}const f=d.ok;if("success"===f.status&&(t.name===at||t.name===ct)){const t=a.path;if("string"==typeof t){const e=t.startsWith("/")?t:r.normalizePath(l(this.workdir,t));this.written.includes(e)||this.written.push(e)}}if("pending"===f.status){const e=null==(i=f.task_id)?void 0:i.trim();return e?r.taskStateObservation(o,e,{kind:"unknown",reason:"this runtime has no task backend"},{kind:"tools"}):{kind:"error",call_id:o,message:`tool \`${t.name}\` returned a pending result without a task_id`,host:r.toHost(f)}}return r.fitResultBudget(f),r.envelopeObservation(o,f,r.applyHints(f,this.ledger,o))}}function Ee(t,e,n){return{runtime_id:t,kind:ge,host:e.host,target:e,workdir:n.cwd,capabilities:{tools:Object.fromEntries(n.tools.map((t=>[t,"available"]))),network:!0,os:n.os}}}function Oe(t){return t.wait_ms<t.timeout_ms}async function Ie(t={}){const e=n.cloneJson(t.config??{env:{}});e.env=e.env??{},function(t){const e=t.kind??ge;if(r.PLANNED_RUNTIME_KINDS.includes(e))throw n.XllmError.capability(`runtime \`${e}\` is planned but not implemented`);if("site"===e)throw n.XllmError.capability("runtime `site` is built by a website (createSiteRuntime); the Deno host runs `native`");if("remote_ssh"===e||"remote_node"===e)throw n.XllmError.capability(`runtime \`${e}\` is not available on the Deno host (only \`native\`)`);if(e!==ge)throw be(`unknown runtime kind \`${e}\``);if(t.remote_ssh&&void 0!==t.kind)throw be("remote_ssh connection block requires kind: remote_ssh");if(t.remote_node&&void 0!==t.kind)throw be("remote_node connection block requires kind: remote_node");if(t.remote_ssh||t.remote_node)throw be("connection block does not match runtime kind");if($e(t.env??{}),void 0!==t.id&&!t.id.trim())throw be("id cannot be empty");if(0===t.task_wait_ms)throw be("task_wait_ms must be positive")}(e);const i=e.workdir??t.workdir??o().cwd();let s;try{s=await o().realPath(i)}catch(_){throw n.XllmError.capability(`runtime cwd ${i}: ${c(_)}`)}if(!(await d(s)))throw n.XllmError.capability("runtime workdir must be a directory");const a=await ve(s,e.env),u=et(await tt(),a.uid),h=rt(e.id,ge,u),f=function(t,e,n,r){const i=t.os.toLowerCase(),o=t.shell.split(/[/\\]/).pop()??"";return{id:e,kind:ge,os:t.os,arch:t.arch,hostname:t.hostname,shell:t.shell,cwd:t.cwd,tools:t.tools,current_time:t.current_time,timezone:t.timezone,target:n,platform:"darwin"===i||"macos"===i?"macos":i,shell_kind:o.replace(/\.exe$/,"").replace(/\.EXE$/,"").toLowerCase(),baseline:r??""}}(a,h,u,e.baseline),m={...e,kind:ge,id:h,workdir:f.cwd},p=Ee(h,u,a),w=l(o().env.get("BUCKYOS_ROOT")||"/opt/buckyos","data"),g=(t,e,i,o,s,a)=>{const c=[];for(const l of t){const t=r.describeToolSource(l);if("mcp"===l.kind)throw n.XllmError.capability(`${e}: \`${t}\`: MCP tools are not available on the Deno host`);if("named"===l.kind)throw n.XllmError.capability(`${e}: \`${t}\`: named host tools are not available on the Deno host (only the \`bash\` group)`);if(l.groupname===r.BUILTIN_TOOL_GROUP_BASH_CORE||"executor"===l.groupname)throw n.XllmError.capability(`${e}: \`${t}\` needs a host task CLI / executor that the Deno host does not provide (use \`bash\`)`);if(l.groupname!==r.BUILTIN_TOOL_GROUP_BASH)throw n.XllmError.tools(`unknown builtin tool group \`${l.groupname}\` (available: ${r.BUILTIN_TOOL_GROUP_BASH}, ${r.BUILTIN_TOOL_GROUP_BASH_CORE}, executor)`);if(Oe(i))throw n.XllmError.capability(`${e}: \`shell\` would hand commands still running after runtime.task_wait_ms (${i.wait_ms} ms) to a task backend, which the Deno host does not have; set runtime.task_wait_ms to at least tools.shell.timeout_ms (${i.timeout_ms} ms) so \`shell\` waits for its command`);const u="workspace"===o,d={root:f.cwd,allowedRead:u?[f.cwd]:[],allowedWrite:u?[f.cwd]:[],dfsRoot:w},h=[Kt(d),Zt(d),Qt(d),we({workspace:f.cwd,restrictCwd:u,timeoutMs:i.timeout_ms,maxTimeoutMs:i.max_timeout_ms,env:s})];for(const e of h){if(a.has(e.spec.name))throw n.XllmError.tools(`tool name \`${e.spec.name}\` from ${t} conflicts with an already expanded tool of the same name`);a.set(e.spec.name,e),c.push({name:e.spec.name,description:e.spec.description,args_schema:n.cloneJson(e.spec.args_schema),source:t})}}return c};let y;return{kind:ge,probe:a,descriptor:()=>n.cloneJson(p),config:()=>n.cloneJson(m),async info(){const t=await ve(f.cwd,m.env),e=y?[...new Set([...f.tools,...y])].sort().slice(0,32):f.tools;return{...n.cloneJson(f),tools:e,current_time:t.current_time,timezone:t.timezone}},async open(e,i){$e(e.env);const o={...m.env,...e.env};o.PATH=o.PATH??a.path;const s=t.takeover&&t.takeover.run_id===e.run_id?t.takeover.tools:void 0,c=s?{enabled:s.enabled,filesystem_policy:s.filesystem_policy,tools2actions:s.tools2actions,tools:s.tool_sources,actions:s.action_sources,bash_tools:s.bash_tools,shell:{timeout_ms:s.shell.timeout_ms,max_timeout_ms:s.shell.max_timeout_ms}}:i,l=c.enabled??!1,u=c.filesystem_policy??"workspace",d=c.tools2actions??!1,h=r.shellSettings(c.shell,e.task_wait_ms),p=e.loop_model,w={enabled:l,filesystem_policy:u,tools2actions:d,tool_sources:n.cloneJson(c.tools??[]),action_sources:n.cloneJson(c.actions??[]),native:[],actions:[],bash_tools:n.cloneJson(c.bash_tools??[]),shell:h,exec_enabled:!1,sources:{...e.sources}};if("function_call"===p){if(d)throw n.XllmError.capability("`tools2actions: true` requires `loop_model: behavior`; function_call cannot convert tools into actions");if((c.actions??[]).length>0)throw n.XllmError.capability("`actions` are configured but `loop_model` is function_call; use `loop_model: behavior` or remove `actions`")}const _=new Map;if(l){const t=c.tools??[{kind:"group",groupname:r.BUILTIN_TOOL_GROUP_BASH}];w.tool_sources=n.cloneJson(t);const e=g(t,"tools.tools",h,u,o,_),i=g(w.action_sources,"tools.actions",h,u,o,_);"behavior"===p&&d?w.actions=[...e,...i]:(w.native=e,w.actions=i),w.exec_enabled=_.has(lt)&&[...w.native,...w.actions].some((t=>t.name===lt))}let v;if(s){v=new Map;for(const t of[...s.native,...s.actions])_.has(t.name)&&v.set(t.name,{name:t.name,description:t.description,args_schema:n.cloneJson(t.args_schema)})}return y=[...w.native,...w.actions].map((t=>t.name)),{tools:w,manager:new xe(_,f.cwd,v)}},async describeInterrupted(t,e){if(e.name!==lt)return r.unresolvedReason(e.name);const n=re(t.run_dir,e.call_id);return void 0===n?Ae(e,void 0,"(no execution directory)"):Ae(e,await Se(n),n)}}}async function Se(t){let e;try{const n=(await o().stat(l(t,"command"))).mtime;n&&(e=Math.floor(n.getTime()))}catch{e=void 0}return{exit_code:await ce(t),stdout_tail:await ae(l(t,"stdout"),ht),stderr_tail:await ae(l(t,"stderr"),ht),exists:await d(t),started_at_ms:e}}function Te(t){let e="";return t.stdout_tail.trim()&&(e+=`\n--- stdout (tail) ---\n${t.stdout_tail.trimEnd()}`),t.stderr_tail.trim()&&(e+=`\n--- stderr (tail) ---\n${t.stderr_tail.trimEnd()}`),e}function Ae(t,e,n){const r=function(t){var e;const n=null==(e=t.args)?void 0:e.command;if("string"!=typeof n)return"";const r=n.split(/\s+/).filter(Boolean).join(" "),i=[...r];return i.length>160?`${i.slice(0,160).join("")}…`:r}(t),i=void 0!==(null==e?void 0:e.started_at_ms)?`started ${ie(Math.max(0,Date.now()-e.started_at_ms))} ago (at ${e.started_at_ms} ms since epoch)`:"start time unknown";return void 0!==(null==e?void 0:e.exit_code)?`shell (native): the previous executor exited while \`${r}\` was running (${i}). The command has since ended with exit code ${e.exit_code} (read from ${n}); its result was never returned, so review it before deciding whether to repeat anything.${Te(e)}`:`shell (native): the previous executor exited while \`${r}\` was running (${i}). The command may have partly executed; it usually ended together with the executor, but not necessarily (e.g. after kill -9 it may still be running). Background processes it started are unaffected. Check the actual state before repeating it.${e?Te(e):""}`}const Le="~/.xllm/runs",Pe="~/.xllm/locks";function Re(t,e){return r.resolveConfigPath(t,e,function(){const t=o().env;return t.get("HOME")??t.get("USERPROFILE")}())}function De(t,e){if("disabled"===(null==t?void 0:t.kind))return;return Re("path"===(null==t?void 0:t.kind)?t.path:Le,u(e.startsWith("/")?e:l(o().cwd(),e)))}class Me{constructor(t,e){this.file=t,this.path=e,this.released=!1}static async tryAcquire(t){try{await o().mkdir(u(t),{recursive:!0})}catch(r){throw n.XllmError.storage(`cannot create lock directory ${u(t)}: ${c(r)}`)}let e;try{e=await o().open(t,{read:!0,write:!0,create:!0})}catch(r){throw n.XllmError.storage(`cannot open lock ${t}: ${c(r)}`)}if(!(await e.tryLock(!0)))return e.close(),null;try{await o().writeTextFile(t,`${o().pid}\n`)}catch{}return new Me(e,t)}async release(){if(!this.released){this.released=!0;try{await this.file.unlock()}finally{this.file.close()}}}}async function Xe(t){let e;try{e=await o().open(t,{read:!0,write:!0,create:!0})}catch{return!1}try{return!(await e.tryLock(!0))||(await e.unlock(),!1)}finally{e.close()}}let je=0;function Ne(t){return String(t).padStart(4,"0")}class Ue{constructor(t){this.persistent=!0,this.dir=Re(t,o().cwd())}runsDir(){return this.dir}runDir(t){return l(this.dir,t)}async ensureWritable(){try{await o().mkdir(this.dir,{recursive:!0})}catch(e){throw n.XllmError.storage(`runs directory ${this.dir} cannot be created: ${c(e)}`)}const t=l(this.dir,`.probe-${o().pid}`);try{await o().writeFile(t,new Uint8Array)}catch(e){throw n.XllmError.storage(`runs directory ${this.dir} is not writable: ${c(e)}`)}await o().remove(t).catch((()=>{}))}async createRun(){await this.ensureWritable();for(let e=0;e<8;e++){const e=r.generateRunId(),i=this.runDir(e);try{await o().mkdir(i)}catch(t){if(a(t))continue;throw n.XllmError.storage(`cannot create run directory ${i}: ${c(t)}`)}return await o().mkdir(l(i,"snapshots"),{recursive:!0}),e}throw n.XllmError.storage("cannot allocate a unique run id")}async writeRecord(t){const e=this.runDir(t.run_id),r=l(e,"run.json"),i=l(e,`run.json.tmp-${o().pid}-${je++}`);try{await o().mkdir(e,{recursive:!0}),await h(i,(new TextEncoder).encode(JSON.stringify(t,null,2)))}catch(s){throw n.XllmError.storage(`write ${i}: ${c(s)}`)}try{await o().rename(i,r)}catch(s){throw n.XllmError.storage(`commit ${r}: ${c(s)}`)}try{await f(e)}catch(s){throw n.XllmError.storage(`sync ${e}: ${c(s)}`)}}async readRecord(t){const e=l(this.runDir(t),"run.json");let i,a;try{i=await o().readTextFile(e)}catch(d){if(s(d))throw new n.XllmError({kind:"run_not_found",run_id:t,runs_dir:this.dir});throw n.XllmError.storage(`read ${e}: ${c(d)}`)}try{a=JSON.parse(i)}catch(d){throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:c(d)})}const u=a;if((null==u?void 0:u.version)!==r.RUN_RECORD_VERSION)throw n.XllmError.notResumable(t,"unsupported run record version");if("string"!=typeof u.run_id||"string"!=typeof u.status||"object"!=typeof u.config||"object"!=typeof u.prompt)throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:"run.json unreadable: missing run_id / status / config / prompt"});return a}async listRecords(){const t=[];let e;try{e=o().readDir(this.dir);for await(const n of e)if(n.isDirectory)try{const e=JSON.parse(await o().readTextFile(l(this.dir,n.name,"run.json")));e&&"string"==typeof e.run_id&&t.push(e)}catch{}}catch(r){if(s(r))return t;throw n.XllmError.storage(`read runs directory ${this.dir}: ${c(r)}`)}return t}async putSnapshot(t,e){const r=l(this.runDir(t),"snapshots");try{await o().mkdir(r,{recursive:!0});const n=await this.listSnapshots(t),i=n.length?n[n.length-1]+1:1,s=l(r,`${Ne(i)}.json`),a=l(r,`${Ne(i)}.json.tmp`);return await h(a,(new TextEncoder).encode(JSON.stringify(e))),await o().rename(a,s),await f(r),i}catch(i){if(i instanceof n.XllmError)throw i;throw n.XllmError.storage(`write snapshot of ${t}: ${c(i)}`)}}async getSnapshot(t,e){const r=l(this.runDir(t),"snapshots",`${Ne(e)}.json`);let i;try{i=await o().readTextFile(r)}catch(s){throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:`snapshot ${e} missing at ${r}: ${c(s)}`})}try{return JSON.parse(i)}catch(s){throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:`snapshot ${e} unreadable: ${c(s)}`})}}async listSnapshots(t){const e=l(this.runDir(t),"snapshots"),n=[];try{for await(const t of o().readDir(e)){const e=/^(\d+)\.json$/.exec(t.name);e&&n.push(Number(e[1]))}}catch(r){if(s(r))return[];throw r}return n.sort(((t,e)=>t-e))}lockRun(t){return Me.tryAcquire(l(this.runDir(t),".lock"))}async isRunLive(t){return!!(await d(this.runDir(t)))&&Xe(l(this.runDir(t),".lock"))}async removeRun(t){const e=this.runDir(t);try{await o().remove(e,{recursive:!0})}catch(r){if(!s(r))throw n.XllmError.storage(`remove ${e}: ${c(r)}`)}await f(this.dir).catch((()=>{}))}async importRun(t){const e=t.record.run_id;if(await this.isRunLive(e))throw new n.XllmError({kind:"run_busy",run_id:e});const r=this.runDir(e);await o().mkdir(l(r,"snapshots"),{recursive:!0});for(const[n,i]of t.snapshots){const t=l(r,"snapshots",`${Ne(n)}.json`),e=`${t}.tmp`;await h(e,(new TextEncoder).encode(JSON.stringify(i))),await o().rename(e,t)}await f(l(r,"snapshots")),await this.writeRecord(t.record)}}function Ce(t=Pe){const e=Re(t,o().cwd());return async(t,n)=>{const r=await Me.tryAcquire(ot(e,t));return r&&await o().writeTextFile(r.path,`${n}\n`).catch((()=>{})),r}}function Fe(t){return d(t)}const He="BUCKYOS_APPCLIENT_SESSION_TOKEN";async function Be(t){if("env"===t.kind){const e=o().env.get(t.name);if(void 0===e)throw n.XllmError.capability(`environment variable \`${t.name}\` is not set`);return e}let e,r;try{e=await o().readTextFile(t.path)}catch(s){throw n.XllmError.capability(`cannot re-read credential source ${t.path}:${t.field}: ${c(s)}`)}try{r=JSON.parse(e)}catch(s){throw n.XllmError.capability(`cannot parse credential source ${t.path} (the Deno host reads JSON configuration): ${c(s)}`)}let i=r;for(const o of t.field.split(".")){if(!n.isObject(i)||!(o in i))throw n.XllmError.capability(`credential field \`${t.field}\` no longer exists in ${t.path}`);i=i[o]}if("string"!=typeof i||!i.trim())throw n.XllmError.capability(`credential field \`${t.field}\` in ${t.path} is empty or not a string`);return i}function ze(t){return{async infer(){throw n.providerError({refused:{code:r.REFUSED_CREDENTIALS}},t)}}}async function qe(t){var e,r,s;if("openai"===(t.kind??"buckyos")){const e=t.api_key?await Be(t.api_key):o().env.get("OPENAI_API_KEY");if(!(null==e?void 0:e.trim()))throw n.XllmError.capability("openai provider: no API key; set `provider.api_key`, `provider.api_key_env` or the OPENAI_API_KEY environment variable");return new i.OpenAiLlmClient({baseUrl:t.base_url,apiKey:e,headers:t.headers})}if(void 0!==t.on_behalf_of&&null!==t.on_behalf_of)throw n.XllmError.capability("buckyos provider: `on_behalf_of` (a system service paying for a user) is not available on the Deno host");const a=t.session_token?await Be(t.session_token):null==(e=o().env.get(He))?void 0:e.trim();if(!a)return ze(`buckyos provider: no BuckyOS session on this host (set ${He}), sign in and resume`);const l=(null==(r=o().env.get("BUCKYOS_APP_ID"))?void 0:r.trim())||"buckycli",u=new((await async function(){const t=new URL("./node.mjs",self.location).href;return await import(t)}()).BuckyOSSDK)("node");try{await u.initBuckyOS(l,{zoneHost:(null==(s=o().env.get("BUCKYOS_ZONE_HOST"))?void 0:s.trim())??"",appId:l,defaultProtocol:"https://",runtimeType:"AppClient",sessionToken:a,privateKeySearchPaths:[],autoRenew:!1})}catch(d){throw n.XllmError.capability(`buckyos provider: cannot initialize the BuckyOS runtime (check zone/session setup): ${c(d)}`)}return new n.AiccLlmClient(u.getAiccClient())}function We(t,e,n,r={}){const i={llm:n,runtime:t,store:e,pid:o().pid,lockWorkdir:Ce(r.lockDir),workdirExists:Fe};return r.observer&&(i.observer=r.observer),r.tokenizer&&(i.tokenizer=r.tokenizer),i}const Je={infer(){throw n.XllmError.other("the model client is created after the task is prepared")}};function Ge(t){const e=t instanceof n.XllmError?t:n.XllmError.capability(t instanceof Error?t.message:String(t)),r=()=>{throw e},i=()=>Promise.reject(e);return{descriptor:r,config:r,info:i,open:i,describeInterrupted:i}}exports.BASH_GROUP_TOOLS=ut,exports.DEFAULT_LOCK_DIR=Pe,exports.DEFAULT_RUNS_DIR=Le,exports.EDIT_FILE_SPEC=Wt,exports.EXEC_MAX_OUTPUT_BYTES=dt,exports.FileLock=Me,exports.FileRunStore=Ue,exports.HOST_ID_ENV=K,exports.LOCAL_PROBE=ye,exports.NATIVE_KIND=ge,exports.NATIVE_WRAPPER=te,exports.NativeToolManager=xe,exports.READ_FILE_SPEC=zt,exports.SESSION_TOKEN_ENV=He,exports.WRITE_FILE_SPEC=qt,exports.blake3Hex=Y,exports.createLlmClient=qe,exports.createNativeRuntime=Ie,exports.credentialsRefusedClient=ze,exports.deriveRuntimeId=rt,exports.execDirFor=re,exports.fmtElapsed=ie,exports.interruptedShellText=Ae,exports.isLocked=Xe,exports.localProbe=ve,exports.nativeDeps=We,exports.nativeDescriptor=Ee,exports.nativeHostId=tt,exports.nativeHostIdFrom=Q,exports.nativeTarget=et,exports.parseProbe=_e,exports.prepareNativeTask=async function(t,e,n,i,o={}){const s=r.mergeConfigLayers([{path:e,file:r.parseLlmContextJson(e,t??null)}]),a=await Ie({config:s.runtime,workdir:o.workdir});let c=o.store;if(!c){const t=De(s.runs_dir,e);c=void 0===t?new r.MemoryRunStore:new Ue(t)}const l=We(a,c,o.llm??Je,o),u=await r.XllmTask.prepare(t,e,n,i,l);return{task:u,deps:{...l,llm:o.llm??await qe(u.config.provider)}}},exports.readExecDir=Se,exports.resolveHostPath=Re,exports.resolveSecret=Be,exports.resumeNativeRun=async function(t,e,i={},o={}){const s=await t.readRecord(e);let a,c=o.llm;if(r.isTerminal(s.status))a=Ge(n.XllmError.other("a terminal run is not executed"));else{try{a=await Ie({config:s.config.runtime,workdir:s.workdir,takeover:{run_id:s.run_id,tools:s.config.tools}})}catch(l){a=Ge(l)}c=c??await qe(s.config.provider)}return r.XllmRun.resume(t,e,i,We(a,t,c??Je,o))},exports.runsDirOf=De,exports.runtimeIdOf=it,exports.sanitizeCallId=ne,exports.shellSpec=he,exports.targetText=nt,exports.workdirExists=Fe,exports.workdirLockPath=ot,exports.workdirLocker=Ce;
|
|
2
2
|
//# sourceMappingURL=xllm_deno.cjs.map
|
package/dist/xllm_deno.mjs
CHANGED
|
@@ -4,9 +4,9 @@ var __publicField = (obj, key, value) => {
|
|
|
4
4
|
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
5
5
|
return value;
|
|
6
6
|
};
|
|
7
|
-
import { n as canonicalJson, i as isObject, X as XllmError, m as cloneJson, p as providerError, A as AiccLlmClient } from "./aicc-
|
|
8
|
-
import { ac as observationText, aH as normalizePath, ae as RESULT_BUDGET_TOKENS, av as MemoryHintLedger, at as HINT_NS_DEDUP, T as ToolDispatchException, ad as toHost, aE as taskStateObservation, aa as fitResultBudget, a6 as envelopeObservation, aw as applyHints, aI as PLANNED_RUNTIME_KINDS, s as shellSettings, aJ as BUILTIN_TOOL_GROUP_BASH, u as unresolvedReason, d as describeToolSource, aK as BUILTIN_TOOL_GROUP_BASH_CORE, aL as resolveConfigPath, g as generateRunId, R as RUN_RECORD_VERSION, Y as REFUSED_CREDENTIALS, q as mergeConfigLayers, w as parseLlmContextJson, G as MemoryRunStore, $ as XllmTask, a2 as isTerminal, _ as XllmRun } from "./site_manager-
|
|
9
|
-
import { O as OpenAiLlmClient } from "./openai-
|
|
7
|
+
import { n as canonicalJson, i as isObject, X as XllmError, m as cloneJson, p as providerError, A as AiccLlmClient } from "./aicc-286ba457.mjs";
|
|
8
|
+
import { ac as observationText, aH as normalizePath, ae as RESULT_BUDGET_TOKENS, av as MemoryHintLedger, at as HINT_NS_DEDUP, T as ToolDispatchException, ad as toHost, aE as taskStateObservation, aa as fitResultBudget, a6 as envelopeObservation, aw as applyHints, aI as PLANNED_RUNTIME_KINDS, s as shellSettings, aJ as BUILTIN_TOOL_GROUP_BASH, u as unresolvedReason, d as describeToolSource, aK as BUILTIN_TOOL_GROUP_BASH_CORE, aL as resolveConfigPath, g as generateRunId, R as RUN_RECORD_VERSION, Y as REFUSED_CREDENTIALS, q as mergeConfigLayers, w as parseLlmContextJson, G as MemoryRunStore, $ as XllmTask, a2 as isTerminal, _ as XllmRun } from "./site_manager-4f1940eb.mjs";
|
|
9
|
+
import { O as OpenAiLlmClient } from "./openai-1c0d8341.mjs";
|
|
10
10
|
import "./krpc_client-673448e5.mjs";
|
|
11
11
|
function deno() {
|
|
12
12
|
const d = globalThis.Deno;
|
package/dist/xllm_dev.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./aicc-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./aicc-342f2659.js"),t=require("./openai-7aa4ffbf.js");require("./krpc_client-26c2dc8b.js");exports.OpenAiLlmClient=t.OpenAiLlmClient,exports.messagesToOpenai=t.messagesToOpenai,exports.openaiHttpFailure=t.openaiHttpFailure,exports.ScriptedLlmClient=class{constructor(e,t={}){this.script=e,this.options=t,this.requests=[],this.index=0}get calls(){return this.index}async infer(t){const s=this.index++;this.requests.push({...t,messages:e.cloneJson(t.messages)});const n=this.script[s];let i;return i=void 0===n?this.options.fallback??{error:{kind:"internal",message:`scripted model has no reply #${s+1}`}}:"function"==typeof n?await n(t,s):n,this.play(i,t,s)}async play(t,s,n){if("hang"in t)return new Promise(((t,n)=>{const i=()=>n(new e.LLMComputeException({kind:"cancelled"}));s.signal.aborted?i():s.signal.addEventListener("abort",i,{once:!0})}));if("delay_ms"in t)return await new Promise((e=>setTimeout(e,t.delay_ms))),this.play(t.then,s,n);if("error"in t)throw new e.LLMComputeException(t.error);const i=t.usage??this.options.usage??{total_tokens:10,request_units:1};if("message"in t)return{message:e.cloneJson(t.message),usage:i};const o=[];void 0!==t.text&&""!==t.text&&o.push({type:"text",text:t.text});let r=0;for(const e of t.tool_calls??[])r+=1,o.push({type:"tool_use",call_id:e.call_id??`call_${n+1}_${r}`,name:e.name,args:e.args??{}});return 0===o.length&&o.push({type:"text",text:""}),{message:{role:"assistant",content:o},usage:i}}};
|
|
2
2
|
//# sourceMappingURL=xllm_dev.cjs.map
|
package/dist/xllm_dev.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { m as cloneJson, L as LLMComputeException } from "./aicc-
|
|
2
|
-
import { O, m, o } from "./openai-
|
|
1
|
+
import { m as cloneJson, L as LLMComputeException } from "./aicc-286ba457.mjs";
|
|
2
|
+
import { O, m, o } from "./openai-1c0d8341.mjs";
|
|
3
3
|
import "./krpc_client-673448e5.mjs";
|
|
4
4
|
class ScriptedLlmClient {
|
|
5
5
|
constructor(script, options = {}) {
|