@crewx/sdk 0.9.0-rc.163 → 0.9.0-rc.165

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/app/app.d.ts +10 -0
  2. package/dist/app/entry.d.ts +2 -0
  3. package/dist/app/index.d.ts +6 -0
  4. package/dist/app/index.js +12 -10
  5. package/dist/app/job-bridge.child.d.ts +1 -0
  6. package/dist/app/job-bridge.d.ts +67 -0
  7. package/dist/app/job-bridge.drain.child.d.ts +1 -0
  8. package/dist/app/job-bridge.example.d.ts +11 -0
  9. package/dist/app/job-contract.d.ts +40 -0
  10. package/dist/app/job-wire.d.ts +149 -0
  11. package/dist/app/runtime.d.ts +2 -0
  12. package/dist/app-artifact-policy/check.d.ts +2 -0
  13. package/dist/app-artifact-policy/contract.d.ts +54 -0
  14. package/dist/app-artifact-policy/helper.d.ts +15 -0
  15. package/dist/app-artifact-policy/index.d.ts +3 -0
  16. package/dist/app-artifact-policy/index.js +18 -0
  17. package/dist/app-artifact-policy/paths.d.ts +24 -0
  18. package/dist/app-artifact-policy/scan.d.ts +47 -0
  19. package/dist/desktop/index.js +3 -3
  20. package/dist/esm/app/index.js +12 -10
  21. package/dist/esm/app-artifact-policy/index.js +18 -0
  22. package/dist/esm/desktop/index.js +3 -3
  23. package/dist/esm/index.js +251 -226
  24. package/dist/esm/plugins/index.js +102 -85
  25. package/dist/esm/process/index.js +1 -1
  26. package/dist/esm/publish/index.js +2 -2
  27. package/dist/esm/repository/index.js +134 -111
  28. package/dist/esm/skills/index.js +2 -2
  29. package/dist/index.browser.d.ts +4 -0
  30. package/dist/index.browser.js +4 -4
  31. package/dist/index.d.ts +14 -2
  32. package/dist/index.js +250 -225
  33. package/dist/mcp-app/app-job-bridge.d.ts +30 -0
  34. package/dist/mcp-app/app-job-bridge.example.d.ts +36 -0
  35. package/dist/mcp-app/app-job.d.ts +168 -0
  36. package/dist/mcp-app/index.d.ts +4 -0
  37. package/dist/mcp-app/skill-backend.d.ts +7 -1
  38. package/dist/migrations/0041_tranquil_vivisector.sql +54 -0
  39. package/dist/migrations/meta/0041_snapshot.json +4156 -0
  40. package/dist/migrations/meta/_journal.json +7 -0
  41. package/dist/plugins/index.js +102 -85
  42. package/dist/process/index.d.ts +2 -2
  43. package/dist/process/index.js +1 -1
  44. package/dist/process/process-control.d.ts +19 -0
  45. package/dist/publish/index.js +2 -2
  46. package/dist/repository/index.d.ts +2 -0
  47. package/dist/repository/index.js +132 -109
  48. package/dist/repository/sidebar-tab.repository.d.ts +82 -0
  49. package/dist/repository/thread.repository.d.ts +10 -0
  50. package/dist/schema/index.d.ts +1 -0
  51. package/dist/schema/sidebar-tabs.d.ts +466 -0
  52. package/dist/skills/index.js +2 -2
  53. package/dist/ui-instance/types.d.ts +6 -0
  54. package/dist/ui-plugin/types.d.ts +4 -1
  55. package/package.json +7 -1
package/dist/app/app.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import type { UiContentMediaType } from './content-media-types.js';
2
2
  import type { AppScheduleDirective, AppScheduleSnapshot, ToolScheduleDeclaration } from './schedule-contract.js';
3
+ import type { AppJobOperation, ToolJobDeclaration } from './job-contract.js';
4
+ import type { AppJobRun, AppJobs } from './job-bridge.js';
3
5
  export type JsonObject = Record<string, unknown>;
4
6
  export type JsonSchema = Readonly<{
5
7
  type: 'object';
@@ -68,6 +70,8 @@ export interface ToolOptions {
68
70
  }>;
69
71
  readonly content?: ToolContentDeclaration;
70
72
  readonly schedule?: ToolScheduleDeclaration;
73
+ readonly job?: ToolJobDeclaration;
74
+ readonly jobAccess?: readonly AppJobOperation[];
71
75
  }
72
76
  export interface AppContext {
73
77
  readonly instanceId: string;
@@ -81,6 +85,8 @@ export interface AppRuntimeOptions<State extends JsonObject = JsonObject> {
81
85
  readonly workspaceRoot: string;
82
86
  readonly context?: AppContext;
83
87
  readonly schedule?: AppScheduleSnapshot;
88
+ readonly jobs?: AppJobs;
89
+ readonly jobRun?: AppJobRun;
84
90
  }
85
91
  export type AppFailureOutcome = 'failed' | 'rejected';
86
92
  export interface AppErrorMapping {
@@ -115,9 +121,13 @@ export declare class CrewXApp<State extends JsonObject = JsonObject> {
115
121
  private answerRange;
116
122
  private readonly callContext;
117
123
  private readonly callSchedule;
124
+ private readonly callJobs;
125
+ private readonly callJobRun;
118
126
  private scheduleDirective;
119
127
  readonly workspaceRoot: string;
120
128
  constructor(options?: AppRuntimeOptions<State>);
129
+ get jobs(): AppJobs | undefined;
130
+ get jobRun(): AppJobRun | undefined;
121
131
  get schedule(): AppScheduleSnapshot | undefined;
122
132
  requestSchedule(enabled: boolean): void;
123
133
  get didRequestSchedule(): AppScheduleDirective | undefined;
@@ -1,7 +1,9 @@
1
1
  import type { JsonObject } from './app.js';
2
+ import type { RunSkillAppOptions } from './runtime.js';
2
3
  export interface AppEntryOptions {
3
4
  readonly sanitize?: (value: unknown) => unknown;
4
5
  readonly emptyState?: JsonObject;
5
6
  readonly inputFd?: number;
7
+ readonly jobBridge?: RunSkillAppOptions['jobBridge'];
6
8
  }
7
9
  export declare function runAppEntry(importApp: () => Promise<unknown>, options?: AppEntryOptions): Promise<void>;
@@ -10,3 +10,9 @@ export { executeAppRequest, runSkillApp } from './runtime.js';
10
10
  export type { AppFailureInfo, RunSkillAppOptions } from './runtime.js';
11
11
  export { runAppEntry } from './entry.js';
12
12
  export type { AppEntryOptions } from './entry.js';
13
+ export { APP_JOB_CAPABILITY, APP_JOB_CAPABILITY_VERSION, APP_JOB_DEADLINE_MS, APP_JOB_MAX_PER_APP, APP_JOB_OPERATIONS, APP_JOB_OUTCOMES, APP_JOB_RUN_REQUIRED, APP_JOB_REFUSAL_CODES, APP_JOB_STATES, APP_JOB_STOP_GRACE_MS, APP_JOB_STOP_REASONS, APP_JOB_TRIGGERS, hasAppJobCapability, isAppJobCode, isAppJobDeadlineMs, isAppJobOperation, isAppJobPhase, } from './job-contract.js';
14
+ export type { AppJobCapabilityDeclaration, AppJobOperation, AppJobOutcome, AppJobRefusalCode, AppJobState, AppJobStopReason, AppJobTrigger, ToolJobDeclaration, } from './job-contract.js';
15
+ export { APP_JOB_BRIDGE_CHANNEL_MAX_BYTES, APP_JOB_BRIDGE_DRAIN_TIMEOUT_MS, APP_JOB_BRIDGE_ENV, APP_JOB_BRIDGE_ERROR_CODES, APP_JOB_BRIDGE_FD, APP_JOB_BRIDGE_MAX_LINE_BYTES, APP_JOB_BRIDGE_REPLY_TIMEOUT_MS, APP_JOB_BRIDGE_VERSION, AppJobLineReader, appJobTriggerForActor, buildAppJobChannelEnvironment, encodeAppJobLine, parseAppJobChannel, parseAppJobControlReply, parseAppJobControlRequest, parseAppJobRunPush, parseAppJobRunReport, parseAppJobView, readAppJobChannel, } from './job-wire.js';
16
+ export type { AppJobBridgeErrorCode, AppJobChannel, AppJobControlReply, AppJobControlRequest, AppJobLineEvent, AppJobRunPush, AppJobRunReport, AppJobView, AppJobWireHandle, } from './job-wire.js';
17
+ export { AppJobBridge, openInheritedAppJobTransport } from './job-bridge.js';
18
+ export type { AppJobBridgeOptions, AppJobLineTransport, AppJobProgress, AppJobRun, AppJobStartOutcome, AppJobStatusOutcome, AppJobStopOutcome, AppJobs, AppJobTransportOpener, } from './job-bridge.js';
package/dist/app/index.js CHANGED
@@ -1,10 +1,12 @@
1
- 'use strict';var util=require('util'),fs=require('fs'),crypto=require('crypto'),console$1=require('console'),stream=require('stream');var D=["text/plain","application/json"];var k=[5,15,30,60],x=Object.freeze({min:15e3,max:6e5,default:3e5}),we=1,z="schedule:",be="schedule",Ie="exit 78",re=["standby","disabled","draining","degraded"],Re=["cron","cron_manual","app_enable"],Ne=/^[A-Z][A-Z0-9_]{0,63}$/u;function ie(e){return typeof e=="string"&&Ne.test(e)}var oe=["status","everyMinutes","lastStartedAt","lastFinishedAt","lastOutcome","lastErrorCode","nextRunAt","periodic","periodicReason"],De=["unset","on","off"],xe=["available","unavailable"],V=64,Pe=128;function ae(e){return k.includes(e)}function W(e){return Number.isSafeInteger(e)&&e>=x.min&&e<=x.max}function se(e){return re.includes(e)}function de(e){if(!ke(e)||Object.keys(e).length!==oe.length||!oe.every(o=>Object.hasOwn(e,o))||typeof e.status!="string"||!De.includes(e.status)||!ae(e.everyMinutes)||!F(e.lastStartedAt,V)||!F(e.lastFinishedAt,V)||!F(e.lastOutcome,Pe)||!F(e.nextRunAt,V)||e.lastErrorCode!==null&&!ie(e.lastErrorCode)||typeof e.periodic!="string"||!xe.includes(e.periodic))return;let t=e.periodic;if(!(t==="available"?e.periodicReason!==null:!se(e.periodicReason))&&!(e.nextRunAt!==null&&(e.status!=="on"||t!=="available")))return Object.freeze({status:e.status,everyMinutes:e.everyMinutes,lastStartedAt:e.lastStartedAt,lastFinishedAt:e.lastFinishedAt,lastOutcome:e.lastOutcome,lastErrorCode:e.lastErrorCode,nextRunAt:e.nextRunAt,periodic:t,periodicReason:e.periodicReason})}function F(e,n){return e===null||typeof e=="string"&&e.length>0&&e.length<=n}function ke(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var ue=Symbol;ue.metadata===void 0&&Object.defineProperty(Symbol,"metadata",{configurable:false,value:Symbol.for("Symbol.metadata")});var Ue=ue.metadata,U=Symbol.for("crewx.app.tool-metadata"),l=class extends Error{code;detail;outcome;constructor(n,t=null,o){super(n),this.name="AppError",this.code=n,this.detail=t,this.outcome=G(o?.outcome);}};function G(e){return e==="rejected"?"rejected":"failed"}var Y=class{static devtools=process.env.CREWX_APP_DEV==="1"?Object.freeze({log:true}):void 0;currentState;stateWasSet=false;answerBody;answerRange;callContext;callSchedule;scheduleDirective;workspaceRoot;constructor(n={workspaceRoot:process.cwd()}){this.currentState=n.state??{},this.workspaceRoot=n.workspaceRoot,this.callContext=n.context===void 0?void 0:ve(n.context),this.callSchedule=n.schedule===void 0?void 0:Object.freeze({...n.schedule});}get schedule(){return this.callSchedule}requestSchedule(n){if(typeof n!="boolean")throw new TypeError("requestSchedule needs true or false");if(this.callSchedule===void 0)throw new l("SCHEDULE_UNSUPPORTED","this App has no schedule on this Host");let t=this.callContext?.actor;if(t==="schedule")throw new l("SCHEDULE_UNSUPPORTED","a scheduled run cannot change its own schedule",{outcome:"rejected"});if(n&&t!=="user")throw new l("SCHEDULE_ENABLE_DENIED","only the person at the screen can turn a schedule on",{outcome:"rejected"});this.scheduleDirective=Object.freeze({enabled:n});}get didRequestSchedule(){return this.scheduleDirective}get context(){if(this.callContext===void 0)throw new TypeError("this.context is only set when the Host runs the action; pass options.context when you construct the App in a test");return this.callContext}get state(){return this.currentState}get didSetState(){return this.stateWasSet}setState(n){this.currentState=n,this.stateWasSet=true;}get didSetContent(){return this.answerBody!==void 0}get producedContent(){return this.answerBody===void 0?void 0:{body:this.answerBody,...this.answerRange===void 0?{}:{range:this.answerRange}}}setContent(n,t){if(typeof n!="string"&&!(n instanceof Uint8Array))throw new TypeError("setContent needs a string or a Uint8Array");if(t!==void 0&&!He(t))throw new TypeError("setContent range must be { startLine, lineCount, totalLines }, three integers of at least 1");this.answerBody=typeof n=="string"?new TextEncoder().encode(n):new Uint8Array(n),this.answerRange=t===void 0?void 0:{startLine:t.startLine,lineCount:t.lineCount,totalLines:t.totalLines};}emptyState(){return {}}validate(n,t,o){}mapError(n){return {code:"EXECUTION_FAILED",detail:null}}errorState(n,t,o){return {...T(o.state)?o.state:{},error:{code:n,detail:t}}}};function Le(e){return function(n,t){if(t.static||t.private||t.kind!=="method")throw new TypeError("@Tool can decorate public instance methods only");let o=t.metadata;if(!o)throw new TypeError("standard decorator metadata is unavailable");let i=Object.hasOwn(o,U)?o[U]:[];if(i.some(u=>u.methodName===String(t.name)))throw new TypeError(`@Tool is declared more than once for ${String(t.name)}`);let r=e.content===void 0?void 0:Me(e.name,e.content),s=e.schedule===void 0?void 0:Fe(e);if(s!==void 0&&i.some(u=>u.options.schedule!==void 0))throw new TypeError(`@Tool ${e.name}: an App declares at most one scheduled action`);o[U]=[...i,{methodName:String(t.name),options:Object.freeze({...e,...r===void 0?{}:{content:r},...s===void 0?{}:{schedule:s}})}];}}function L(e){let n=e[Ue],t=n&&Object.hasOwn(n,U)?n[U]:[],o=new Map(t.map(r=>[r.methodName,r])),i=Object.getOwnPropertyNames(e.prototype).map(r=>o.get(r)).filter(r=>r!==void 0);if(i.length!==t.length)throw new TypeError("a @Tool method is missing from the App prototype");return i}function ce(e){return L(e).some(({options:n})=>n.schedule!==void 0)}function le(e){let n=e.definition,t=L(e),o=new Set;return t.map(({options:i})=>{if(o.has(i.name))throw new TypeError(`duplicate @Tool name: ${i.name}`);return o.add(i.name),{actionId:i.name,...i.dataInputs===void 0?{}:{dataInputs:[...i.dataInputs]},confirmation:i.confirmation??"none",capability:i.capability??"app.read",mutation:i.mutation??true,inputSchema:i.inputSchema,...i.content===void 0?{}:{content:Xe(i.content)},...i.schedule===void 0?{}:{schedule:{...i.schedule}},resultProjection:i.resultProjection??{allow:[...n.stateProjection.allow]},_meta:{description:i.description}}})}function je(e,n){if(n.length===0)throw new TypeError("backendCommand must name the skill command");let t=le(e).map(({_meta:o,...i})=>({...i,backend:{type:"skill",command:[...n]},_meta:o}));return {...e.definition,actions:t}}function Me(e,n){let t=r=>{throw new TypeError(`@Tool ${e}: content ${r}`)},o=(r,s,u)=>{if(!T(u))return t(`${r} must be an object`);for(let a of Object.keys(u))if(a==="mediaType"){if(!D.includes(u[a]))return t(`${r}.mediaType must be one of ${D.join(", ")}`)}else if(a===s){if(typeof u[a]!="boolean")return t(`${r}.${a} must be true or false`)}else return t(`${r} has the unknown key "${a}"`);return Object.hasOwn(u,"mediaType")?Object.freeze({...u}):t(`${r}.mediaType is required`)};if(!T(n))return t("must be an object");let i={};for(let r of Object.keys(n))if(r==="in")i[r]=o("in","required",n[r]);else if(r==="out")i[r]=o("out","range",n[r]);else return t(`has the unknown key "${r}"; use "in" and/or "out"`);return Object.keys(i).length===0?t('needs "in" and/or "out"'):Object.freeze(i)}function Fe(e){let n=o=>{throw new TypeError(`@Tool ${e.name}: schedule ${o}`)},t=e.schedule;if(!T(t))return n("must be an object");for(let o of Object.keys(t))if(o!=="everyMinutes"&&o!=="timeoutMs")return n(`has the unknown key "${o}"`);return k.includes(t.everyMinutes)?t.timeoutMs!==void 0&&!W(t.timeoutMs)?n(`timeoutMs must be an integer from ${x.min} to ${x.max}`):e.content!==void 0?n("cannot be combined with content"):e.dataInputs!==void 0?n("cannot be combined with dataInputs"):e.confirmation!==void 0&&e.confirmation!=="none"?n("cannot require a native confirmation"):Object.freeze({everyMinutes:t.everyMinutes,...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs}}):n(`everyMinutes must be one of ${k.join(", ")}`)}function ve(e){return Object.freeze({instanceId:e.instanceId,threadId:e.threadId,actor:e.actor,requestId:e.requestId,nowMs:e.nowMs})}function Xe(e){let n={};for(let[t,o]of Object.entries(e))n[t]={...o};return n}function He(e){return T(e)&&["startLine","lineCount","totalLines"].every(n=>Number.isSafeInteger(e[n])&&e[n]>=1)}function T(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var Je=/^[A-Za-z0-9._:-]{1,128}$/u,qe=/[\u0000-\u001f\u007f\u2028\u2029]/u,Ke=512;function Q(e=process.env){let n=pe(e.CREWX_APP_INSTANCE_ID),t=e.CREWX_APP_REQUEST_ID,o=e.CREWX_APP_ACTOR_KIND,i=e.CREWX_APP_NOW_MS;if(n===void 0||typeof t!="string"||!Je.test(t)||o!=="user"&&o!=="agent"&&o!=="schedule"||typeof i!="string"||!/^\d{1,16}$/u.test(i))return;let r=Number(i);if(!Number.isSafeInteger(r))return;let s=e.CREWX_THREAD_ID===void 0?null:pe(e.CREWX_THREAD_ID);if(s!==void 0&&!(o==="schedule"&&(s!==null||!n.startsWith(z))))return Object.freeze({instanceId:n,threadId:s,actor:o,requestId:t,nowMs:r})}function pe(e){if(!(typeof e!="string"||e.length===0||qe.test(e)))return new TextEncoder().encode(e).byteLength<=Ke?e:void 0}var $e="dist/tools.json",Be=1,Ve="dist/main.mjs";var fe=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];function ze(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!fe.some(o=>o===t)||n.has(t))return false;n.add(t);}return true}var v=2,X=2097152;var P=2*1024*1024,H=2e4;function Z(e){return crypto.createHash("sha256").update(e).digest("hex")}function J(e){if(e.byteLength===0)return 0;let n=0;for(let t of e)t===10&&(n+=1);return e[e.byteLength-1]!==10&&(n+=1),n}var Ge=X+1+P,Qe=64*1024,Ze=10,q={kind:"invalid"};function en(e,n){try{let t=[],o=0;for(;;){let s=new Uint8Array(Qe),u=fs.readSync(e,s,0,s.length,null);if(u===0)break;if(o+=u,o>n)return;t.push(s.subarray(0,u));}let i=new Uint8Array(o),r=0;for(let s of t)i.set(s,r),r+=s.byteLength;return i}catch{return}}function K(e){return nn(en(e,Ge))}function nn(e){if(e===void 0)return q;let n=e.indexOf(Ze);if(e.byteLength<=X){let o=dn(Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"));if(o.ok&&!(n>=0&&b(o.value)&&o.value.schemaVersion===v))return {kind:"v1",value:o.value}}if(n<=0||n>X)return q;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e.subarray(0,n)));}catch{return q}return !b(t)||t.schemaVersion!==v?q:{kind:"v2",header:t,body:e.subarray(n+1)}}var tn="actionId,content,input,schemaVersion,state",on="bytes,lines,mediaType,sha256",rn="mediaType,range",an=/^[a-f0-9]{64}$/u,sn=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});function Ee(e,n){let t=a=>({code:a,outcome:"rejected"});if(j(e)!==tn||e.schemaVersion!==v||typeof e.actionId!="string"||!b(e.input)||!b(e.state)||!b(e.content)||j(e.content)!=="in,out")return {code:"INPUT_INVALID",outcome:"failed"};let o=e.content,i,r=o.in;if(r===null){if(n.byteLength!==0)return t(n.byteLength>P?"CONTENT_TOO_LARGE":"CONTENT_DIGEST_MISMATCH")}else {if(!b(r)||j(r)!==on||!ye(r.mediaType)||!me(r.bytes,P)||!me(r.lines,H)||typeof r.sha256!="string"||!an.test(r.sha256)||n.byteLength!==r.bytes)return t(n.byteLength>P?"CONTENT_TOO_LARGE":"CONTENT_DIGEST_MISMATCH");if(Z(n)!==r.sha256||J(n)!==r.lines)return t("CONTENT_DIGEST_MISMATCH");let a;try{a=sn.decode(n);}catch{return t("CONTENT_ENCODING_INVALID")}i={mediaType:r.mediaType,text:a};}let s,u=o.out;if(u!==null){if(!b(u)||j(u)!==rn||!ye(u.mediaType))return t("CONTENT_SOURCE_UNSUPPORTED");let a=u.range;if(a!==null&&!un(a))return t("CONTENT_SOURCE_UNSUPPORTED");s={mediaType:u.mediaType,...a===null?{}:{range:{startLine:a.startLine,lineCount:a.lineCount}}};}return {actionId:e.actionId,input:e.input,state:e.state,content:{...i===void 0?{}:{in:i},...s===void 0?{}:{out:s}}}}function Ae(e){return Object.hasOwn(e,"code")}function Se(e,n){let t=o=>({code:o,outcome:"rejected"});if(e?.in===void 0){if(n.in!==void 0)return t("CONTENT_SOURCE_UNSUPPORTED")}else if(n.in===void 0){if(e.in.required===true)return t("CONTENT_REQUIRED")}else if(n.in.mediaType!==e.in.mediaType)return t("CONTENT_SOURCE_UNSUPPORTED");if(e?.out===void 0){if(n.out!==void 0)return t("CONTENT_SOURCE_UNSUPPORTED")}else {if(n.out===void 0)return t("CONTENT_REQUIRED");if(n.out.mediaType!==e.out.mediaType||n.out.range!==void 0&&e.out.range!==true)return t("CONTENT_SOURCE_UNSUPPORTED")}}function $(e,n){let{content:t,...o}=e,i=n===void 0?o:{...o,content:{bytes:n.body.byteLength,lines:J(n.body),sha256:Z(n.body),...n.range===void 0?{}:{range:n.range}}},r=new TextEncoder().encode(`${JSON.stringify(i)}
2
- `);if(n===void 0)return r;let s=new Uint8Array(r.byteLength+n.body.byteLength);return s.set(r,0),s.set(n.body,r.byteLength),s}function he(e){if(e.body.byteLength>P||J(e.body)>H)return {code:"CONTENT_TOO_LARGE",outcome:"failed"}}function dn(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}function j(e){return Object.keys(e).sort().join(",")}function b(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function ye(e){return typeof e=="string"&&D.includes(e)}function me(e,n){return Number.isSafeInteger(e)&&e>=0&&e<=n}function un(e){return b(e)&&j(e)==="lineCount,startLine"&&Number.isSafeInteger(e.startLine)&&e.startLine>=1&&Number.isSafeInteger(e.lineCount)&&e.lineCount>=1&&e.lineCount<=H}var ln=1;async function pn(e,n,t=process.env.CREWX_WORKSPACE_ROOT??process.cwd(),o){return (await _e(e,n,t,void 0,true,void 0,o)).response}async function _e(e,n,t,o,i=true,r,s){let u=r!==void 0,a=T(n)?n:void 0,E=a?.input,A=a?.state,d=new e({state:T(A)?A:{},workspaceRoot:t,...s===void 0?{}:{context:s}}),h=T(E)?E:{},S=T(A)?A:d.emptyState(),f={},y=a!==void 0&&Object.hasOwn(a,"schedule"),C;try{let m;if(u){if(a===void 0||y)throw new l("INPUT_INVALID");let p=Ee(a,r);if(Ae(p))throw new l(p.code,null,{outcome:p.outcome});(({actionId:m,input:h,state:S}=p)),f=p.content;}else {let p=y&&a!==void 0?de(a.schedule):void 0;if(!a||Object.keys(a).length!==(y?5:4)||!["schemaVersion","actionId","input","state"].every(ge=>Object.hasOwn(a,ge))||a.schemaVersion!==ln||typeof a.actionId!="string"||!T(E)||!T(A)||y&&p===void 0)throw new l("INPUT_INVALID");m=a.actionId,h=E,S=A,C=p;}d=new e({state:S,workspaceRoot:t,...s===void 0?{}:{context:s},...C===void 0?{}:{schedule:C}}),await d.validate(m,h,S);let c=L(e).find(({options:p})=>p.name===m);if(!c)throw new l("INPUT_INVALID");if(C!==void 0&&(c.options.content!==void 0||!ce(e)))throw new l("INPUT_INVALID");let g=d[c.methodName];if(typeof g!="function")throw new l("EXECUTION_FAILED");let _=Se(c.options.content,f);if(_)throw new l(_.code,null,{outcome:_.outcome});let M=Object.freeze({...f.in===void 0?{}:{in:Object.freeze({text:f.in.text})},...f.out===void 0?{}:{out:Object.freeze(f.out.range===void 0?{}:{range:Object.freeze({...f.out.range})})}}),N=()=>g.call(d,h,M),I=i?await yn(N):await N();if(I!==void 0&&!T(I))throw new l("EXECUTION_FAILED");let w;if(f.out!==void 0){if(w=d.producedContent,w===void 0)throw new l("EXECUTION_FAILED","content.out was requested but setContent was never called");let p=he(w);if(p)throw new l(p.code,null,{outcome:p.outcome})}else if(d.didSetContent)throw new l("EXECUTION_FAILED","setContent was called but the request asked for no content.out");let R=d.didRequestSchedule;return {response:{...d.didSetState?{state:d.state}:{},...I===void 0?{}:{result:I},...R===void 0?{}:{schedule:{enabled:R.enabled}}},...w===void 0?{}:{answer:w}}}catch(m){let c,g=m,_=m instanceof l?m:void 0;if(_)c={code:_.code,detail:_.detail,outcome:_.outcome};else try{c=d.mapError(m);}catch(p){c={code:"EXECUTION_FAILED",detail:null},g=p;}let M=En(c?.code),N=M?c.code:"EXECUTION_FAILED",I=typeof c?.detail=="string"?c.detail:null,w=M?G(c.outcome):"failed",R;try{R=d.errorState(N,I,{input:h,state:S});}catch(p){g=new AggregateError([g,p],"App error handling failed"),R=d.emptyState();}return o?.(N,g,{outcome:w,detail:I,expected:_!==void 0&&g===_}),{response:{outcome:w,errorCode:N,state:T(R)?R:d.emptyState()}}}}async function fn(e,n={}){let t=n.output??process.stdout,o,i;if(n.preloadedInput!==void 0)o=n.preloadedInput.value,i=n.preloadedInput.body;else {let d=K(n.inputFd??0);d.kind==="v1"?o=d.value:d.kind==="v2"&&(o=d.header,i=d.body);}let r=i!==void 0,s=n.context??Q(),u=false,a=(d,h,S)=>{u=true,n.onFailure?.(d,h,S);},E;try{E=await _e(e,o,process.env.CREWX_WORKSPACE_ROOT??process.cwd(),a,n.consoleManaged!==!0,i,s);}catch(d){a("EXECUTION_FAILED",d),E={response:Te(n.emptyState)};}mn(E.response)&&!u&&a(E.response.errorCode,void 0,{outcome:E.response.outcome,detail:null,expected:false});let A;try{let d=(n.sanitize??Ce)(E.response);A=r?$(d,E.answer):`${JSON.stringify(d)}
3
- `;}catch(d){a("EXECUTION_FAILED",d);let h=Te(n.emptyState);try{let S=(n.sanitize??Ce)(h);A=r?$(S):`${JSON.stringify(S)}
4
- `;}catch(S){a("EXECUTION_FAILED",S),A=r?$(h):`${JSON.stringify(h)}
5
- `;}}t.write(A);}async function yn(e){let n=["log","info","debug"],t=new Map;for(let o of n)t.set(o,console[o]),console[o]=(...i)=>process.stderr.write(`${util.format(...i)}
6
- `);try{return await e()}finally{for(let o of n)console[o]=t.get(o);}}function Te(e={}){return {outcome:"failed",errorCode:"EXECUTION_FAILED",state:{...e,error:{code:"EXECUTION_FAILED",detail:null}}}}function mn(e){return (e.outcome==="failed"||e.outcome==="rejected")&&typeof e.errorCode=="string"}function En(e){return typeof e=="string"&&/^[A-Z][A-Z0-9_]{0,127}$/u.test(e)}function Ce(e){return e}var ee={depth:null,maxArrayLength:null,maxStringLength:null},te=class extends stream.Writable{#e="buffer";#n=[];_write(n,t,o){if(this.#e==="buffer"){this.#n.push(typeof n=="string"?n:Uint8Array.from(n)),o();return}if(this.#e==="discard"){o();return}process.stderr.write(n,o);}flushToStderr(){this.#e="stderr";for(let n of this.#n)process.stderr.write(n);this.#n=[];}discard(){this.#e="discard",this.#n=[];}};async function hn(e,n={}){let t=process.stdout,o=t.write.bind(t),i=new te,r=new console$1.Console({stdout:i,stderr:i,inspectOptions:{...ee}});globalThis.console=r;let s=false,u="-",a="-",E,A=false,d,h;try{let y=Cn(n.inputFd??0);u=_n(y.value),a=B(process.env.CREWX_APP_REQUEST_ID),E=new Date().toISOString();try{d=await e();}catch(c){A=!0,h=c;}let C=d?.default;if(!A&&C?.devtools?.log===!0?(Object.assign(util.inspect.defaultOptions,ee),S(E),i.flushToStderr()):i.discard(),A){f("EXECUTION_FAILED",h),ne(o,n,f);return}try{if(typeof d?.runSkillApp!="function")throw new TypeError("App module does not export runSkillApp");let c={sanitize:n.sanitize,emptyState:n.emptyState??Tn(C),preloadedInput:y.body===void 0?{value:y.value}:{value:y.value,body:y.body},onFailure:f,consoleManaged:!0,output:{write:o}};await d.runSkillApp(C,c);}catch(c){f("EXECUTION_FAILED",c),ne(o,n,f);}}catch(y){f("EXECUTION_FAILED",y),ne(o,n,f);}finally{process.exitCode=0;}function S(y){s||(process.stderr.write(`[crewx-app] ${y??new Date().toISOString()} ${B(u)} req=${a}
7
- `),s=true);}function f(y,C,m){S();let c=m?.expected===true&&m.detail?` ${B(m.detail)}`:"";process.stderr.write(`[crewx-app] ${m?.outcome??"failed"} ${B(y)}${c}
8
- `),C!==void 0&&m?.expected!==true&&process.stderr.write(`${util.inspect(C,ee)}
9
- `);}}function Tn(e){if(typeof e=="function")try{let t=new e({workspaceRoot:process.cwd()}).emptyState();return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function Cn(e){let n=K(e);return n.kind==="v1"?{value:n.value}:n.kind==="v2"?{value:n.header,body:n.body}:{value:void 0}}function _n(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&typeof e.actionId=="string"?e.actionId:"-"}function B(e){return typeof e!="string"||e.length===0?"-":e.replace(/[\u0000-\u001f\u007f\u2028\u2029]/gu,"_")}function ne(e,n,t){let o={code:"EXECUTION_FAILED",detail:null},r={outcome:"failed",errorCode:"EXECUTION_FAILED",state:n.emptyState!==null&&typeof n.emptyState=="object"&&!Array.isArray(n.emptyState)?{...n.emptyState,error:o}:{error:o}},s=r;try{s=(n.sanitize??On)(r);}catch(u){t("EXECUTION_FAILED",u);}e(`${JSON.stringify(s)}
10
- `);}function On(e){return e}exports.APP_SCHEDULE_ACTOR_KIND=be;exports.APP_SCHEDULE_INERT_COMMAND=Ie;exports.APP_SCHEDULE_INSTANCE_PREFIX=z;exports.APP_SCHEDULE_INTERVALS_MINUTES=k;exports.APP_SCHEDULE_MAX_PER_APP=we;exports.APP_SCHEDULE_PERIODIC_REASONS=re;exports.APP_SCHEDULE_TIMEOUT_MS=x;exports.APP_TOOLS_FILE=$e;exports.APP_TOOLS_SCHEMA_VERSION=Be;exports.APP_TOOL_ENTRY=Ve;exports.AppError=l;exports.CrewXApp=Y;exports.SCHEDULE_TRIGGERS=Re;exports.SKILL_BACKEND_ENV_NAMES=fe;exports.Tool=Le;exports.executeAppRequest=pn;exports.generateManifest=je;exports.generateToolDeclarations=le;exports.getToolDeclarations=L;exports.isAppScheduleCode=ie;exports.isAppScheduleIntervalMinutes=ae;exports.isAppSchedulePeriodicReason=se;exports.isAppScheduleTimeoutMs=W;exports.isSkillBackendEnv=ze;exports.readAppContext=Q;exports.runAppEntry=hn;exports.runSkillApp=fn;
1
+ 'use strict';var util=require('util'),fs=require('fs'),crypto=require('crypto'),net=require('net'),console$1=require('console'),stream=require('stream');var N=["text/plain","application/json"];var q=[5,15,30,60],x=Object.freeze({min:15e3,max:6e5,default:3e5}),hn=1,Ae="schedule:",En="schedule",On="exit 78",Fe=["standby","disabled","draining","degraded"],gn=["cron","cron_manual","app_enable"],Sn=/^[A-Z][A-Z0-9_]{0,63}$/u;function qe(n){return typeof n=="string"&&Sn.test(n)}var Me=["status","everyMinutes","lastStartedAt","lastFinishedAt","lastOutcome","lastErrorCode","nextRunAt","periodic","periodicReason"],Tn=["unset","on","off"],Rn=["available","unavailable"],ye=64,In=128;function He(n){return q.includes(n)}function be(n){return Number.isSafeInteger(n)&&n>=x.min&&n<=x.max}function Xe(n){return Fe.includes(n)}function Ge(n){if(!Pn(n)||Object.keys(n).length!==Me.length||!Me.every(o=>Object.hasOwn(n,o))||typeof n.status!="string"||!Tn.includes(n.status)||!He(n.everyMinutes)||!Y(n.lastStartedAt,ye)||!Y(n.lastFinishedAt,ye)||!Y(n.lastOutcome,In)||!Y(n.nextRunAt,ye)||n.lastErrorCode!==null&&!qe(n.lastErrorCode)||typeof n.periodic!="string"||!Rn.includes(n.periodic))return;let t=n.periodic;if(!(t==="available"?n.periodicReason!==null:!Xe(n.periodicReason))&&!(n.nextRunAt!==null&&(n.status!=="on"||t!=="available")))return Object.freeze({status:n.status,everyMinutes:n.everyMinutes,lastStartedAt:n.lastStartedAt,lastFinishedAt:n.lastFinishedAt,lastOutcome:n.lastOutcome,lastErrorCode:n.lastErrorCode,nextRunAt:n.nextRunAt,periodic:t,periodicReason:n.periodicReason})}function Y(n,e){return n===null||typeof n=="string"&&n.length>0&&n.length<=e}function Pn(n){if(n===null||typeof n!="object"||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}var k=Object.freeze({min:6e4,max:18e5,default:6e5}),wn=Object.freeze({min:1e3,max:12e4,default:3e4}),Cn=1,Ve="crewx/appJobs",$e=1,me=["starting","running","stopping","finished"],_e=["succeeded","failed","timed_out","cancelled","shutdown","interrupted"],Q=["cancelled","timed_out","shutdown"],he=["manual","schedule"],Jn=/^[a-z][a-z0-9_]{0,63}$/u,Dn=/^[A-Z][A-Z0-9_]{0,63}$/u,Z=["start","status","cancel"],Ee=["APP_JOB_NOT_DECLARED","APP_JOB_NOT_AUTHORIZED","APP_JOB_SELF_START","APP_JOB_OWNER_INVALID","APP_JOB_DEFINITION_INVALID","APP_JOB_DEFINITION_CHANGED","APP_JOB_DEADLINE_INVALID","APP_JOB_SHUTTING_DOWN","APP_JOB_OWNER_MISMATCH","APP_JOB_STALE_HANDLE","APP_JOB_NOT_ACTIVE","APP_JOB_NOT_GRANTED"],Oe="APP_JOB_RUN_REQUIRED";function ge(n){return Number.isSafeInteger(n)&&n>=k.min&&n<=k.max}function j(n){return typeof n=="string"&&Dn.test(n)}function L(n){return typeof n=="string"&&Jn.test(n)}function H(n){return Z.includes(n)}function Nn(n){return n?.some(({name:e,version:t})=>e===Ve&&t===$e)===true}var ze=Symbol;ze.metadata===void 0&&Object.defineProperty(Symbol,"metadata",{configurable:false,value:Symbol.for("Symbol.metadata")});var xn=ze.metadata,X=Symbol.for("crewx.app.tool-metadata"),l=class extends Error{code;detail;outcome;constructor(e,t=null,o){super(e),this.name="AppError",this.code=e,this.detail=t,this.outcome=Te(o?.outcome);}};function Te(n){return n==="rejected"?"rejected":"failed"}var Se=class{static devtools=process.env.CREWX_APP_DEV==="1"?Object.freeze({log:true}):void 0;currentState;stateWasSet=false;answerBody;answerRange;callContext;callSchedule;callJobs;callJobRun;scheduleDirective;workspaceRoot;constructor(e={workspaceRoot:process.cwd()}){this.currentState=e.state??{},this.workspaceRoot=e.workspaceRoot,this.callContext=e.context===void 0?void 0:Mn(e.context),this.callSchedule=e.schedule===void 0?void 0:Object.freeze({...e.schedule}),this.callJobs=e.jobs,this.callJobRun=e.jobRun;}get jobs(){return this.callJobs}get jobRun(){return this.callJobRun}get schedule(){return this.callSchedule}requestSchedule(e){if(typeof e!="boolean")throw new TypeError("requestSchedule needs true or false");if(this.callSchedule===void 0)throw new l("SCHEDULE_UNSUPPORTED","this App has no schedule on this Host");let t=this.callContext?.actor;if(t==="schedule")throw new l("SCHEDULE_UNSUPPORTED","a scheduled run cannot change its own schedule",{outcome:"rejected"});if(e&&t!=="user")throw new l("SCHEDULE_ENABLE_DENIED","only the person at the screen can turn a schedule on",{outcome:"rejected"});this.scheduleDirective=Object.freeze({enabled:e});}get didRequestSchedule(){return this.scheduleDirective}get context(){if(this.callContext===void 0)throw new TypeError("this.context is only set when the Host runs the action; pass options.context when you construct the App in a test");return this.callContext}get state(){return this.currentState}get didSetState(){return this.stateWasSet}setState(e){this.currentState=e,this.stateWasSet=true;}get didSetContent(){return this.answerBody!==void 0}get producedContent(){return this.answerBody===void 0?void 0:{body:this.answerBody,...this.answerRange===void 0?{}:{range:this.answerRange}}}setContent(e,t){if(typeof e!="string"&&!(e instanceof Uint8Array))throw new TypeError("setContent needs a string or a Uint8Array");if(t!==void 0&&!qn(t))throw new TypeError("setContent range must be { startLine, lineCount, totalLines }, three integers of at least 1");this.answerBody=typeof e=="string"?new TextEncoder().encode(e):new Uint8Array(e),this.answerRange=t===void 0?void 0:{startLine:t.startLine,lineCount:t.lineCount,totalLines:t.totalLines};}emptyState(){return {}}validate(e,t,o){}mapError(e){return {code:"EXECUTION_FAILED",detail:null}}errorState(e,t,o){return {...h(o.state)?o.state:{},error:{code:e,detail:t}}}};function kn(n){return function(e,t){if(t.static||t.private||t.kind!=="method")throw new TypeError("@Tool can decorate public instance methods only");let o=t.metadata;if(!o)throw new TypeError("standard decorator metadata is unavailable");let r=Object.hasOwn(o,X)?o[X]:[];if(r.some(u=>u.methodName===String(t.name)))throw new TypeError(`@Tool is declared more than once for ${String(t.name)}`);let s=n.content===void 0?void 0:Ln(n.name,n.content),i=n.schedule===void 0?void 0:Bn(n);if(i!==void 0&&r.some(u=>u.options.schedule!==void 0))throw new TypeError(`@Tool ${n.name}: an App declares at most one scheduled action`);let a=n.job===void 0?void 0:Un(n);if(a!==void 0&&r.some(u=>u.options.job!==void 0))throw new TypeError(`@Tool ${n.name}: an App declares at most one job action`);let p=n.jobAccess===void 0?void 0:vn(n);o[X]=[...r,{methodName:String(t.name),options:Object.freeze({...n,...s===void 0?{}:{content:s},...i===void 0?{}:{schedule:i},...a===void 0?{}:{job:a},...p===void 0?{}:{jobAccess:p}})}];}}function G(n){let e=n[xn],t=e&&Object.hasOwn(e,X)?e[X]:[],o=new Map(t.map(s=>[s.methodName,s])),r=Object.getOwnPropertyNames(n.prototype).map(s=>o.get(s)).filter(s=>s!==void 0);if(r.length!==t.length)throw new TypeError("a @Tool method is missing from the App prototype");return r}function We(n){return G(n).some(({options:e})=>e.schedule!==void 0)}function Ke(n){let e=n.definition,t=G(n),o=new Set;return t.map(({options:r})=>{if(o.has(r.name))throw new TypeError(`duplicate @Tool name: ${r.name}`);return o.add(r.name),{actionId:r.name,...r.dataInputs===void 0?{}:{dataInputs:[...r.dataInputs]},confirmation:r.confirmation??"none",capability:r.capability??"app.read",mutation:r.mutation??true,inputSchema:r.inputSchema,...r.content===void 0?{}:{content:Fn(r.content)},...r.schedule===void 0?{}:{schedule:{...r.schedule}},...r.job===void 0?{}:{job:{...r.job}},...r.jobAccess===void 0?{}:{jobAccess:[...r.jobAccess]},resultProjection:r.resultProjection??{allow:[...e.stateProjection.allow]},_meta:{description:r.description}}})}function jn(n,e){if(e.length===0)throw new TypeError("backendCommand must name the skill command");let t=Ke(n).map(({_meta:o,...r})=>({...r,backend:{type:"skill",command:[...e]},_meta:o}));return {...n.definition,actions:t}}function Ln(n,e){let t=s=>{throw new TypeError(`@Tool ${n}: content ${s}`)},o=(s,i,a)=>{if(!h(a))return t(`${s} must be an object`);for(let p of Object.keys(a))if(p==="mediaType"){if(!N.includes(a[p]))return t(`${s}.mediaType must be one of ${N.join(", ")}`)}else if(p===i){if(typeof a[p]!="boolean")return t(`${s}.${p} must be true or false`)}else return t(`${s} has the unknown key "${p}"`);return Object.hasOwn(a,"mediaType")?Object.freeze({...a}):t(`${s}.mediaType is required`)};if(!h(e))return t("must be an object");let r={};for(let s of Object.keys(e))if(s==="in")r[s]=o("in","required",e[s]);else if(s==="out")r[s]=o("out","range",e[s]);else return t(`has the unknown key "${s}"; use "in" and/or "out"`);return Object.keys(r).length===0?t('needs "in" and/or "out"'):Object.freeze(r)}function Bn(n){let e=o=>{throw new TypeError(`@Tool ${n.name}: schedule ${o}`)},t=n.schedule;if(!h(t))return e("must be an object");for(let o of Object.keys(t))if(o!=="everyMinutes"&&o!=="timeoutMs")return e(`has the unknown key "${o}"`);return q.includes(t.everyMinutes)?t.timeoutMs!==void 0&&!be(t.timeoutMs)?e(`timeoutMs must be an integer from ${x.min} to ${x.max}`):n.content!==void 0?e("cannot be combined with content"):n.dataInputs!==void 0?e("cannot be combined with dataInputs"):n.confirmation!==void 0&&n.confirmation!=="none"?e("cannot require a native confirmation"):Object.freeze({everyMinutes:t.everyMinutes,...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs}}):e(`everyMinutes must be one of ${q.join(", ")}`)}function Un(n){let e=o=>{throw new TypeError(`@Tool ${n.name}: job ${o}`)},t=n.job;if(!h(t))return e("must be an object");for(let o of Object.keys(t))if(o!=="deadlineMs")return e(`has the unknown key "${o}"`);return t.deadlineMs!==void 0&&!ge(t.deadlineMs)?e(`deadlineMs must be an integer from ${k.min} to ${k.max}`):n.content!==void 0?e("cannot be combined with content"):n.dataInputs!==void 0?e("cannot be combined with dataInputs"):n.confirmation!==void 0&&n.confirmation!=="none"?e("cannot require a native confirmation"):n.schedule!==void 0?e("cannot be the scheduled action too"):n.jobAccess!==void 0?e("cannot also be a control action: a run does not control itself"):Object.freeze({...t.deadlineMs===void 0?{}:{deadlineMs:t.deadlineMs}})}function vn(n){let e=o=>{throw new TypeError(`@Tool ${n.name}: jobAccess ${o}`)},t=n.jobAccess;return !Array.isArray(t)||t.length===0?e("must list at least one operation"):new Set(t).size!==t.length?e("must not repeat an operation"):t.every(H)?n.job!==void 0?e("cannot be set on the job action, which runs the job and cannot control it"):n.content!==void 0?e("cannot be combined with content"):Object.freeze([...t]):e("names an unknown operation")}function Mn(n){return Object.freeze({instanceId:n.instanceId,threadId:n.threadId,actor:n.actor,requestId:n.requestId,nowMs:n.nowMs})}function Fn(n){let e={};for(let[t,o]of Object.entries(n))e[t]={...o};return e}function qn(n){return h(n)&&["startLine","lineCount","totalLines"].every(e=>Number.isSafeInteger(n[e])&&n[e]>=1)}function h(n){if(n===null||typeof n!="object"||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}var Hn=/^[A-Za-z0-9._:-]{1,128}$/u,Xn=/[\u0000-\u001f\u007f\u2028\u2029]/u,Gn=512;function Re(n=process.env){let e=Ye(n.CREWX_APP_INSTANCE_ID),t=n.CREWX_APP_REQUEST_ID,o=n.CREWX_APP_ACTOR_KIND,r=n.CREWX_APP_NOW_MS;if(e===void 0||typeof t!="string"||!Hn.test(t)||o!=="user"&&o!=="agent"&&o!=="schedule"||typeof r!="string"||!/^\d{1,16}$/u.test(r))return;let s=Number(r);if(!Number.isSafeInteger(s))return;let i=n.CREWX_THREAD_ID===void 0?null:Ye(n.CREWX_THREAD_ID);if(i!==void 0&&!(o==="schedule"&&(i!==null||!e.startsWith(Ae))))return Object.freeze({instanceId:e,threadId:i,actor:o,requestId:t,nowMs:s})}function Ye(n){if(!(typeof n!="string"||n.length===0||Xn.test(n)))return new TextEncoder().encode(n).byteLength<=Gn?n:void 0}var Vn="dist/tools.json",$n=1,zn="dist/main.mjs";var Qe=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];function Wn(n){if(!Array.isArray(n)||n.length===0)return false;let e=new Set;for(let t of n){if(!Qe.some(o=>o===t)||e.has(t))return false;e.add(t);}return true}var ee=2,ne=2097152;var B=2*1024*1024,te=2e4;function Ie(n){return crypto.createHash("sha256").update(n).digest("hex")}function oe(n){if(n.byteLength===0)return 0;let e=0;for(let t of n)t===10&&(e+=1);return n[n.byteLength-1]!==10&&(e+=1),e}var Qn=ne+1+B,Zn=64*1024,et=10,re={kind:"invalid"};function nt(n,e){try{let t=[],o=0;for(;;){let i=new Uint8Array(Zn),a=fs.readSync(n,i,0,i.length,null);if(a===0)break;if(o+=a,o>e)return;t.push(i.subarray(0,a));}let r=new Uint8Array(o),s=0;for(let i of t)r.set(i,s),s+=i.byteLength;return r}catch{return}}function ie(n){return tt(nt(n,Qn))}function tt(n){if(n===void 0)return re;let e=n.indexOf(et);if(n.byteLength<=ne){let o=dt(Buffer.from(n.buffer,n.byteOffset,n.byteLength).toString("utf8"));if(o.ok&&!(e>=0&&J(o.value)&&o.value.schemaVersion===ee))return {kind:"v1",value:o.value}}if(e<=0||e>ne)return re;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n.subarray(0,e)));}catch{return re}return !J(t)||t.schemaVersion!==ee?re:{kind:"v2",header:t,body:n.subarray(e+1)}}var ot="actionId,content,input,schemaVersion,state",rt="bytes,lines,mediaType,sha256",it="mediaType,range",st=/^[a-f0-9]{64}$/u,at=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});function nn(n,e){let t=p=>({code:p,outcome:"rejected"});if(V(n)!==ot||n.schemaVersion!==ee||typeof n.actionId!="string"||!J(n.input)||!J(n.state)||!J(n.content)||V(n.content)!=="in,out")return {code:"INPUT_INVALID",outcome:"failed"};let o=n.content,r,s=o.in;if(s===null){if(e.byteLength!==0)return t(e.byteLength>B?"CONTENT_TOO_LARGE":"CONTENT_DIGEST_MISMATCH")}else {if(!J(s)||V(s)!==rt||!Ze(s.mediaType)||!en(s.bytes,B)||!en(s.lines,te)||typeof s.sha256!="string"||!st.test(s.sha256)||e.byteLength!==s.bytes)return t(e.byteLength>B?"CONTENT_TOO_LARGE":"CONTENT_DIGEST_MISMATCH");if(Ie(e)!==s.sha256||oe(e)!==s.lines)return t("CONTENT_DIGEST_MISMATCH");let p;try{p=at.decode(e);}catch{return t("CONTENT_ENCODING_INVALID")}r={mediaType:s.mediaType,text:p};}let i,a=o.out;if(a!==null){if(!J(a)||V(a)!==it||!Ze(a.mediaType))return t("CONTENT_SOURCE_UNSUPPORTED");let p=a.range;if(p!==null&&!ut(p))return t("CONTENT_SOURCE_UNSUPPORTED");i={mediaType:a.mediaType,...p===null?{}:{range:{startLine:p.startLine,lineCount:p.lineCount}}};}return {actionId:n.actionId,input:n.input,state:n.state,content:{...r===void 0?{}:{in:r},...i===void 0?{}:{out:i}}}}function tn(n){return Object.hasOwn(n,"code")}function on(n,e){let t=o=>({code:o,outcome:"rejected"});if(n?.in===void 0){if(e.in!==void 0)return t("CONTENT_SOURCE_UNSUPPORTED")}else if(e.in===void 0){if(n.in.required===true)return t("CONTENT_REQUIRED")}else if(e.in.mediaType!==n.in.mediaType)return t("CONTENT_SOURCE_UNSUPPORTED");if(n?.out===void 0){if(e.out!==void 0)return t("CONTENT_SOURCE_UNSUPPORTED")}else {if(e.out===void 0)return t("CONTENT_REQUIRED");if(e.out.mediaType!==n.out.mediaType||e.out.range!==void 0&&n.out.range!==true)return t("CONTENT_SOURCE_UNSUPPORTED")}}function se(n,e){let{content:t,...o}=n,r=e===void 0?o:{...o,content:{bytes:e.body.byteLength,lines:oe(e.body),sha256:Ie(e.body),...e.range===void 0?{}:{range:e.range}}},s=new TextEncoder().encode(`${JSON.stringify(r)}
2
+ `);if(e===void 0)return s;let i=new Uint8Array(s.byteLength+e.body.byteLength);return i.set(s,0),i.set(e.body,s.byteLength),i}function rn(n){if(n.body.byteLength>B||oe(n.body)>te)return {code:"CONTENT_TOO_LARGE",outcome:"failed"}}function dt(n){try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}}function V(n){return Object.keys(n).sort().join(",")}function J(n){if(n===null||typeof n!="object"||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function Ze(n){return typeof n=="string"&&N.includes(n)}function en(n,e){return Number.isSafeInteger(n)&&n>=0&&n<=e}function ut(n){return J(n)&&V(n)==="lineCount,startLine"&&Number.isSafeInteger(n.startLine)&&n.startLine>=1&&Number.isSafeInteger(n.lineCount)&&n.lineCount>=1&&n.lineCount<=te}var an="CREWX_APP_JOB_CHANNEL",S=1,$=4096,Ce=1e4,Je=5e3,De=512,Pe=Object.freeze({min:3,max:16}),pt=["APP_JOB_BRIDGE_UNAVAILABLE","APP_JOB_BRIDGE_INVALID","APP_JOB_BRIDGE_TIMEOUT","APP_JOB_BRIDGE_CLOSED"],W=/^[A-Za-z0-9._:-]{1,128}$/u,lt=64,dn=2147483647,z=class{#e="";#n=false;push(e){let t=[],o=e;for(;;){let r=o.indexOf(`
3
+ `);if(r===-1)return this.#n||(this.#e+=o,U(this.#e)>$&&(t.push({kind:"oversized"}),this.#e="",this.#n=true)),t;let s=o.slice(0,r);if(o=o.slice(r+1),this.#n){this.#n=false;continue}let i=this.#e+s;this.#e="",t.push(U(i)>$?{kind:"oversized"}:{kind:"line",line:i});}}};function ue(n){let e=JSON.stringify(n);if(U(e)>$)throw new TypeError("App job bridge message is over the line bound");return e}function ct(n){let e=pe(n);if(e===void 0||e.v!==S||!un(e.requestId)||!pn(e.seq))return;let t={v:S,requestId:e.requestId,seq:e.seq};switch(e.op){case "start":return _(e,["v","op","requestId","seq"],[])?{...t,op:"start"}:void 0;case "status":{if(!_(e,["v","op","requestId","seq"],["handle"]))return;if(e.handle===void 0)return {...t,op:"status"};let o=we(e.handle);return o===void 0?void 0:{...t,op:"status",handle:o}}case "cancel":{if(!_(e,["v","op","requestId","seq","handle"],[]))return;let o=we(e.handle);return o===void 0?void 0:{...t,op:"cancel",handle:o}}default:return}}function Ne(n){let e=pe(n);if(e===void 0||e.v!==S||!un(e.requestId)||!pn(e.seq))return;let t={v:S,requestId:e.requestId,seq:e.seq};if(e.ok===false)return _(e,["v","requestId","seq","ok","code"],[])&&Ee.includes(e.code)?{...t,ok:false,code:e.code}:void 0;if(e.ok===true)switch(e.op){case "start":{if(!_(e,["v","requestId","seq","ok","op","outcome","job"],[]))return;let o=ae(e.job),r=e.outcome;return o===void 0||r!=="started"&&r!=="attached"?void 0:{...t,ok:true,op:"start",outcome:r,job:o}}case "status":{if(!_(e,["v","requestId","seq","ok","op","job"],[]))return;if(e.job===null)return {...t,ok:true,op:"status",job:null};let o=ae(e.job);return o===void 0?void 0:{...t,ok:true,op:"status",job:o}}case "cancel":{if(!_(e,["v","requestId","seq","ok","op","outcome","job"],[]))return;let o=ae(e.job);return o===void 0||e.outcome!=="stopping"?void 0:{...t,ok:true,op:"cancel",outcome:"stopping",job:o}}default:return}}function ft(n){let e=pe(n);if(e===void 0||e.v!==S||typeof e.runId!="string"||!W.test(e.runId)||!ce(e.generation))return;let t={v:S,runId:e.runId,generation:e.generation};switch(e.kind){case "heartbeat":return _(e,["v","kind","runId","generation"],[])?{...t,kind:"heartbeat"}:void 0;case "completed":return _(e,["v","kind","runId","generation"],[])?{...t,kind:"completed"}:void 0;case "progress":{if(!_(e,["v","kind","runId","generation","phase"],["completed","total","resumable"]))return;let{completed:o,total:r,resumable:s}=e;return !L(e.phase)||o!==void 0&&!de(o)||r!==void 0&&!de(r)||o!==void 0&&r!==void 0&&o>r||s!==void 0&&typeof s!="boolean"?void 0:{...t,kind:"progress",phase:e.phase,...o===void 0?{}:{completed:o},...r===void 0?{}:{total:r},...s===void 0?{}:{resumable:s}}}case "failed":return _(e,["v","kind","runId","generation","code","recoverable"],[])&&j(e.code)&&typeof e.recoverable=="boolean"?{...t,kind:"failed",code:e.code,recoverable:e.recoverable}:void 0;default:return}}function xe(n){let e=pe(n);if(!(e===void 0||!_(e,["v","kind","runId","generation","reason"],[])||e.v!==S||e.kind!=="stop"||typeof e.runId!="string"||!W.test(e.runId)||!ce(e.generation)||!Q.includes(e.reason)))return {v:S,kind:"stop",runId:e.runId,generation:e.generation,reason:e.reason}}function ke(n){let e=le(n)?n:void 0;if(!(e===void 0||e.v!==S||!mt(e.fd))){if(e.role==="control"){let t=e.operations;return !_(e,["v","role","fd","operations"],[])||!Array.isArray(t)||t.length===0||new Set(t).size!==t.length||!t.every(H)?void 0:{v:1,role:"control",fd:e.fd,operations:[...t]}}if(e.role==="run")return !_(e,["v","role","fd","runId","generation"],[])||typeof e.runId!="string"||!W.test(e.runId)||!ce(e.generation)?void 0:{v:1,role:"run",fd:e.fd,runId:e.runId,generation:e.generation}}}function je(n){let e=n[an];if(typeof e!="string"||U(e)>De)return;let t;try{t=JSON.parse(e);}catch{return}return ke(t)}function yt(n){let e=ke(JSON.parse(JSON.stringify(n)));if(e===void 0)throw new TypeError("App job channel descriptor is invalid");let t=JSON.stringify(e);if(U(t)>De)throw new TypeError("App job channel descriptor is over its bound");return Object.freeze({CREWX_APP_JOB_CHANNEL:t})}function At(n){return n==="schedule"?"schedule":"manual"}function bt(n){return ae(n)}function ae(n){let e=le(n)?n:void 0;if(e===void 0||!_(e,["handle","state","stopReason","trigger","outcome","phase","completed","total","resumable","lastHeartbeatAt","startedAt","finishedAt","errorCode","recoverable"],[]))return;let t=we(e.handle),o=e.stopReason,r=e.outcome,s=e.phase,i=e.errorCode,a=e.recoverable;if(!(t===void 0||!me.includes(e.state)||!(o===null||Q.includes(o))||o!==null&&e.state!=="stopping"||!he.includes(e.trigger)||!(r===null||_e.includes(r))||!(s===null||L(s))||!(e.completed===null||de(e.completed))||!(e.total===null||de(e.total))||typeof e.resumable!="boolean"||!sn(e.lastHeartbeatAt)||!ln(e.startedAt)||!sn(e.finishedAt)||!(i===null||j(i))||!(a===null||typeof a=="boolean")))return {handle:t,state:e.state,stopReason:o,trigger:e.trigger,outcome:r,phase:s,completed:e.completed,total:e.total,resumable:e.resumable,lastHeartbeatAt:e.lastHeartbeatAt,startedAt:e.startedAt,finishedAt:e.finishedAt,errorCode:i,recoverable:a}}function we(n){if(!(!le(n)||!_(n,["runId","generation"],[]))&&!(typeof n.runId!="string"||!W.test(n.runId)||!ce(n.generation)))return {runId:n.runId,generation:n.generation}}function pe(n){if(U(n)>$)return;let e;try{e=JSON.parse(n);}catch{return}return le(e)?e:void 0}function _(n,e,t){let o=new Set([...e,...t]);return Object.keys(n).every(r=>o.has(r))&&e.every(r=>Object.hasOwn(n,r))}function le(n){if(n===null||typeof n!="object"||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function un(n){return typeof n=="string"&&W.test(n)}function pn(n){return Number.isSafeInteger(n)&&n>=1&&n<=dn}function ce(n){return Number.isSafeInteger(n)&&n>=1&&n<=dn}function mt(n){return Number.isSafeInteger(n)&&n>=Pe.min&&n<=Pe.max}function de(n){return Number.isSafeInteger(n)&&n>=0}function ln(n){return typeof n=="string"&&n.length>0&&n.length<=lt}function sn(n){return n===null||ln(n)}function U(n){return new TextEncoder().encode(n).byteLength}var Et=2147483647,v=class{#e;#n;#p;#y=crypto.randomUUID();#A=new z;#r=new Map;#s=new Set;#t;#l=0;#o=false;#c=false;#a=false;#d=null;constructor(e){this.#e=e.channel,this.#n=e.open??fn,this.#p=e.replyTimeoutMs??Ce;}jobsFor(e){let t=this.#e;if(t.role!=="control"||e===void 0)return;let o=t.operations,r=Z.filter(i=>e.includes(i)&&o.includes(i));if(r.length===0)return;let s=i=>{if(!r.includes(i))throw new l("APP_JOB_NOT_GRANTED",null,{outcome:"rejected"})};return Object.freeze({granted:Object.freeze(r),start:async()=>{s("start");let i=await this.#u("start",{});if(i.ok===false)return {kind:"refused",code:i.code};if(i.op!=="start")throw new l("APP_JOB_BRIDGE_INVALID",null,{outcome:"failed"});return {kind:i.outcome,job:i.job}},status:async i=>{s("status");let a=await this.#u("status",i===void 0?{}:{handle:i});if(a.ok===false)return {kind:"refused",code:a.code};if(a.op!=="status")throw new l("APP_JOB_BRIDGE_INVALID",null,{outcome:"failed"});return {kind:"status",job:a.job}},cancel:async i=>{s("cancel");let a=await this.#u("cancel",{handle:i});if(a.ok===false)return {kind:"refused",code:a.code};if(a.op!=="cancel")throw new l("APP_JOB_BRIDGE_INVALID",null,{outcome:"failed"});return {kind:"stopping",job:a.job}}})}runFor(e){let t=this.#e;if(t.role!=="run"||!e)return;try{this.#f();}catch{return}let o={v:S,runId:t.runId,generation:t.generation},r=()=>this.#d,s=i=>{this.#o||this.#c||this.#t===void 0||this.#t.write(ue({...o,...i}));};return Object.freeze({handle:Object.freeze({runId:t.runId,generation:t.generation}),get stopRequested(){return r()!==null},get stopReason(){return r()},progress:i=>{if(!L(i.phase))throw new TypeError("progress phase must be a lower snake case name");if(i.completed!==void 0&&!cn(i.completed))throw new TypeError("progress completed must be a count");if(i.total!==void 0&&!cn(i.total))throw new TypeError("progress total must be a count");if(i.completed!==void 0&&i.total!==void 0&&i.completed>i.total)throw new TypeError("progress completed cannot exceed total");if(i.resumable!==void 0&&typeof i.resumable!="boolean")throw new TypeError("progress resumable must be boolean");this.#a||s({kind:"progress",phase:i.phase,...i.completed===void 0?{}:{completed:i.completed},...i.total===void 0?{}:{total:i.total},...i.resumable===void 0?{}:{resumable:i.resumable}});},heartbeat:()=>{this.#a||s({kind:"heartbeat"});},complete:()=>{s({kind:"completed"}),this.#a=true;},fail:(i,a)=>{if(!j(i))throw new TypeError("fail code must be an upper snake case code");if(typeof a!="boolean")throw new TypeError("fail recoverable must be boolean");s({kind:"failed",code:i,recoverable:a}),this.#a=true;},onStop:i=>{let a=r();return a!==null?(i(a),()=>{}):(this.#s.add(i),()=>{this.#s.delete(i);})}})}close(){this.#i("APP_JOB_BRIDGE_CLOSED");}async drain(e=Je){if(this.#o)return;this.#c=true;let t=this.#t,o;try{if(t!==void 0){let r;try{r=t.drain();}catch{r=Promise.resolve();}await Promise.race([r.catch(()=>{}),new Promise(s=>{o=setTimeout(s,e);})]);}}finally{clearTimeout(o),this.close();}}#u(e,t){let o=this.#f(),r=this.#l+1;if(r>Et)throw new l("APP_JOB_BRIDGE_CLOSED",null,{outcome:"failed"});this.#l=r;let s=`${this.#y}.${r}`,i=ue({v:S,op:e,requestId:s,seq:r,...t});return new Promise((a,p)=>{let u=setTimeout(()=>this.#i("APP_JOB_BRIDGE_TIMEOUT"),this.#p);this.#r.set(r,{op:e,requestId:s,resolve:a,reject:p,timer:u}),o.write(i);})}#f(){if(this.#o)throw new l("APP_JOB_BRIDGE_CLOSED",null,{outcome:"failed"});if(this.#t!==void 0)return this.#t;let e;try{e=this.#n(this.#e.fd);}catch{throw new l("APP_JOB_BRIDGE_UNAVAILABLE",null,{outcome:"failed"})}return e.onData(t=>this.#b(t)),e.onEnd(()=>this.#i("APP_JOB_BRIDGE_CLOSED")),this.#t=e,e}#b(e){for(let t of this.#A.push(e)){if(this.#o)return;if(this.#e.role==="run")t.kind==="line"&&this.#_(t.line);else if(t.kind==="oversized"){this.#i("APP_JOB_BRIDGE_INVALID");return}else this.#m(t.line);}}#m(e){let t=Ne(e),o=t===void 0?void 0:this.#r.get(t.seq);if(t===void 0||o===void 0||o.requestId!==t.requestId||t.ok&&t.op!==o.op){this.#i("APP_JOB_BRIDGE_INVALID");return}clearTimeout(o.timer),this.#r.delete(t.seq),o.resolve(t);}#_(e){let t=this.#e;if(t.role!=="run")return;let o=xe(e);if(!(o===void 0||o.runId!==t.runId||o.generation!==t.generation)&&this.#d===null){this.#d=o.reason;for(let r of [...this.#s])try{r(o.reason);}catch{}}}#i(e){if(this.#o)return;this.#o=true;let t=[...this.#r.values()];this.#r.clear();for(let r of t)clearTimeout(r.timer),r.reject(new l(e,null,{outcome:"failed"}));this.#s.clear();let o=this.#t;this.#t=void 0,o?.close();}};function fn(n){let e=new net.Socket({fd:n,readable:true,writable:true});return e.setEncoding("utf8"),e.on("error",()=>{}),{write:t=>{e.write(`${t}
4
+ `);},drain:()=>new Promise(t=>{if(e.destroyed){t();return}e.write("",()=>t());}),onData:t=>{e.on("data",t);},onEnd:t=>{e.on("close",t);},close:()=>{e.destroy();}}}function cn(n){return Number.isSafeInteger(n)&&n>=0}var gt=1;async function St(n,e,t=process.env.CREWX_WORKSPACE_ROOT??process.cwd(),o){return (await bn(n,e,t,void 0,true,void 0,o)).response}async function bn(n,e,t,o,r=true,s,i,a){let p=s!==void 0,u=h(e)?e:void 0,b=u?.input,m=u?.state,d=new n({state:h(m)?m:{},workspaceRoot:t,...i===void 0?{}:{context:i}}),E=h(b)?b:{},c=h(m)?m:d.emptyState(),f={},T=u!==void 0&&Object.hasOwn(u,"schedule"),R;try{let A;if(p){if(u===void 0||T)throw new l("INPUT_INVALID");let O=nn(u,s);if(tn(O))throw new l(O.code,null,{outcome:O.outcome});(({actionId:A,input:E,state:c}=O)),f=O.content;}else {let O=T&&u!==void 0?Ge(u.schedule):void 0;if(!u||Object.keys(u).length!==(T?5:4)||!["schemaVersion","actionId","input","state"].every(_n=>Object.hasOwn(u,_n))||u.schemaVersion!==gt||typeof u.actionId!="string"||!h(b)||!h(m)||T&&O===void 0)throw new l("INPUT_INVALID");A=u.actionId,E=b,c=m,R=O;}let y=G(n).find(({options:O})=>O.name===A),C=y===void 0?void 0:a?.jobsFor(y.options.jobAccess),I=y===void 0?void 0:a?.runFor(y.options.job!==void 0);if(d=new n({state:c,workspaceRoot:t,...i===void 0?{}:{context:i},...R===void 0?{}:{schedule:R},...C===void 0?{}:{jobs:C},...I===void 0?{}:{jobRun:I}}),await d.validate(A,E,c),!y)throw new l("INPUT_INVALID");if(R!==void 0&&(y.options.content!==void 0||!We(n)))throw new l("INPUT_INVALID");let M=d[y.methodName];if(typeof M!="function")throw new l("EXECUTION_FAILED");let D=on(y.options.content,f);if(D)throw new l(D.code,null,{outcome:D.outcome});if(y.options.job!==void 0&&I===void 0)throw new l(Oe,null,{outcome:"rejected"});let K=Object.freeze({...f.in===void 0?{}:{in:Object.freeze({text:f.in.text})},...f.out===void 0?{}:{out:Object.freeze(f.out.range===void 0?{}:{range:Object.freeze({...f.out.range})})}}),F=()=>M.call(d,E,K),P=r?await Pt(F):await F();if(P!==void 0&&!h(P))throw new l("EXECUTION_FAILED");let w;if(f.out!==void 0){if(w=d.producedContent,w===void 0)throw new l("EXECUTION_FAILED","content.out was requested but setContent was never called");let O=rn(w);if(O)throw new l(O.code,null,{outcome:O.outcome})}else if(d.didSetContent)throw new l("EXECUTION_FAILED","setContent was called but the request asked for no content.out");let ve=d.didRequestSchedule;return {response:{...d.didSetState?{state:d.state}:{},...P===void 0?{}:{result:P},...ve===void 0?{}:{schedule:{enabled:ve.enabled}}},...w===void 0?{}:{answer:w}}}catch(A){let y,C=A,I=A instanceof l?A:void 0;if(I)y={code:I.code,detail:I.detail,outcome:I.outcome};else try{y=d.mapError(A);}catch(w){y={code:"EXECUTION_FAILED",detail:null},C=w;}let M=Ct(y?.code),D=M?y.code:"EXECUTION_FAILED",K=typeof y?.detail=="string"?y.detail:null,F=M?Te(y.outcome):"failed",P;try{P=d.errorState(D,K,{input:E,state:c});}catch(w){C=new AggregateError([C,w],"App error handling failed"),P=d.emptyState();}return o?.(D,C,{outcome:F,detail:K,expected:I!==void 0&&C===I}),{response:{outcome:F,errorCode:D,state:h(P)?P:d.emptyState()}}}}async function Tt(n,e={}){let t=Rt(e.jobBridge);try{await It(n,e,t);}finally{await t?.drain();}}function Rt(n){if(n===null)return;if(n!==void 0)return new v(n);let e=je(process.env);return e===void 0?void 0:new v({channel:e})}async function It(n,e,t){let o=e.output??process.stdout,r,s;if(e.preloadedInput!==void 0)r=e.preloadedInput.value,s=e.preloadedInput.body;else {let d=ie(e.inputFd??0);d.kind==="v1"?r=d.value:d.kind==="v2"&&(r=d.header,s=d.body);}let i=s!==void 0,a=e.context??Re(),p=false,u=(d,E,c)=>{p=true,e.onFailure?.(d,E,c);},b;try{b=await bn(n,r,process.env.CREWX_WORKSPACE_ROOT??process.cwd(),u,e.consoleManaged!==!0,s,a,t);}catch(d){u("EXECUTION_FAILED",d),b={response:yn(e.emptyState)};}wt(b.response)&&!p&&u(b.response.errorCode,void 0,{outcome:b.response.outcome,detail:null,expected:false});let m;try{let d=(e.sanitize??An)(b.response);m=i?se(d,b.answer):`${JSON.stringify(d)}
5
+ `;}catch(d){u("EXECUTION_FAILED",d);let E=yn(e.emptyState);try{let c=(e.sanitize??An)(E);m=i?se(c):`${JSON.stringify(c)}
6
+ `;}catch(c){u("EXECUTION_FAILED",c),m=i?se(E):`${JSON.stringify(E)}
7
+ `;}}o.write(m);}async function Pt(n){let e=["log","info","debug"],t=new Map;for(let o of e)t.set(o,console[o]),console[o]=(...r)=>process.stderr.write(`${util.format(...r)}
8
+ `);try{return await n()}finally{for(let o of e)console[o]=t.get(o);}}function yn(n={}){return {outcome:"failed",errorCode:"EXECUTION_FAILED",state:{...n,error:{code:"EXECUTION_FAILED",detail:null}}}}function wt(n){return (n.outcome==="failed"||n.outcome==="rejected")&&typeof n.errorCode=="string"}function Ct(n){return typeof n=="string"&&/^[A-Z][A-Z0-9_]{0,127}$/u.test(n)}function An(n){return n}var Le={depth:null,maxArrayLength:null,maxStringLength:null},Ue=class extends stream.Writable{#e="buffer";#n=[];_write(e,t,o){if(this.#e==="buffer"){this.#n.push(typeof e=="string"?e:Uint8Array.from(e)),o();return}if(this.#e==="discard"){o();return}process.stderr.write(e,o);}flushToStderr(){this.#e="stderr";for(let e of this.#n)process.stderr.write(e);this.#n=[];}discard(){this.#e="discard",this.#n=[];}};async function Nt(n,e={}){let t=process.stdout,o=t.write.bind(t),r=new Ue,s=new console$1.Console({stdout:r,stderr:r,inspectOptions:{...Le}});globalThis.console=s;let i=false,a="-",p="-",u,b=false,m,d;try{let f=kt(e.inputFd??0);a=jt(f.value),p=fe(process.env.CREWX_APP_REQUEST_ID),u=new Date().toISOString();try{m=await n();}catch(A){b=!0,d=A;}let T=m?.default;if(!b&&T?.devtools?.log===!0?(Object.assign(util.inspect.defaultOptions,Le),E(u),r.flushToStderr()):r.discard(),b){c("EXECUTION_FAILED",d),Be(o,e,c);return}try{if(typeof m?.runSkillApp!="function")throw new TypeError("App module does not export runSkillApp");let A={sanitize:e.sanitize,emptyState:e.emptyState??xt(T),preloadedInput:f.body===void 0?{value:f.value}:{value:f.value,body:f.body},onFailure:c,consoleManaged:!0,output:{write:o},jobBridge:e.jobBridge};await m.runSkillApp(T,A);}catch(A){c("EXECUTION_FAILED",A),Be(o,e,c);}}catch(f){c("EXECUTION_FAILED",f),Be(o,e,c);}finally{process.exitCode=0;}function E(f){i||(process.stderr.write(`[crewx-app] ${f??new Date().toISOString()} ${fe(a)} req=${p}
9
+ `),i=true);}function c(f,T,R){E();let A=R?.expected===true&&R.detail?` ${fe(R.detail)}`:"";process.stderr.write(`[crewx-app] ${R?.outcome??"failed"} ${fe(f)}${A}
10
+ `),T!==void 0&&R?.expected!==true&&process.stderr.write(`${util.inspect(T,Le)}
11
+ `);}}function xt(n){if(typeof n=="function")try{let t=new n({workspaceRoot:process.cwd()}).emptyState();return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function kt(n){let e=ie(n);return e.kind==="v1"?{value:e.value}:e.kind==="v2"?{value:e.header,body:e.body}:{value:void 0}}function jt(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&typeof n.actionId=="string"?n.actionId:"-"}function fe(n){return typeof n!="string"||n.length===0?"-":n.replace(/[\u0000-\u001f\u007f\u2028\u2029]/gu,"_")}function Be(n,e,t){let o={code:"EXECUTION_FAILED",detail:null},s={outcome:"failed",errorCode:"EXECUTION_FAILED",state:e.emptyState!==null&&typeof e.emptyState=="object"&&!Array.isArray(e.emptyState)?{...e.emptyState,error:o}:{error:o}},i=s;try{i=(e.sanitize??Lt)(s);}catch(a){t("EXECUTION_FAILED",a);}n(`${JSON.stringify(i)}
12
+ `);}function Lt(n){return n}exports.APP_JOB_BRIDGE_CHANNEL_MAX_BYTES=De;exports.APP_JOB_BRIDGE_DRAIN_TIMEOUT_MS=Je;exports.APP_JOB_BRIDGE_ENV=an;exports.APP_JOB_BRIDGE_ERROR_CODES=pt;exports.APP_JOB_BRIDGE_FD=Pe;exports.APP_JOB_BRIDGE_MAX_LINE_BYTES=$;exports.APP_JOB_BRIDGE_REPLY_TIMEOUT_MS=Ce;exports.APP_JOB_BRIDGE_VERSION=S;exports.APP_JOB_CAPABILITY=Ve;exports.APP_JOB_CAPABILITY_VERSION=$e;exports.APP_JOB_DEADLINE_MS=k;exports.APP_JOB_MAX_PER_APP=Cn;exports.APP_JOB_OPERATIONS=Z;exports.APP_JOB_OUTCOMES=_e;exports.APP_JOB_REFUSAL_CODES=Ee;exports.APP_JOB_RUN_REQUIRED=Oe;exports.APP_JOB_STATES=me;exports.APP_JOB_STOP_GRACE_MS=wn;exports.APP_JOB_STOP_REASONS=Q;exports.APP_JOB_TRIGGERS=he;exports.APP_SCHEDULE_ACTOR_KIND=En;exports.APP_SCHEDULE_INERT_COMMAND=On;exports.APP_SCHEDULE_INSTANCE_PREFIX=Ae;exports.APP_SCHEDULE_INTERVALS_MINUTES=q;exports.APP_SCHEDULE_MAX_PER_APP=hn;exports.APP_SCHEDULE_PERIODIC_REASONS=Fe;exports.APP_SCHEDULE_TIMEOUT_MS=x;exports.APP_TOOLS_FILE=Vn;exports.APP_TOOLS_SCHEMA_VERSION=$n;exports.APP_TOOL_ENTRY=zn;exports.AppError=l;exports.AppJobBridge=v;exports.AppJobLineReader=z;exports.CrewXApp=Se;exports.SCHEDULE_TRIGGERS=gn;exports.SKILL_BACKEND_ENV_NAMES=Qe;exports.Tool=kn;exports.appJobTriggerForActor=At;exports.buildAppJobChannelEnvironment=yt;exports.encodeAppJobLine=ue;exports.executeAppRequest=St;exports.generateManifest=jn;exports.generateToolDeclarations=Ke;exports.getToolDeclarations=G;exports.hasAppJobCapability=Nn;exports.isAppJobCode=j;exports.isAppJobDeadlineMs=ge;exports.isAppJobOperation=H;exports.isAppJobPhase=L;exports.isAppScheduleCode=qe;exports.isAppScheduleIntervalMinutes=He;exports.isAppSchedulePeriodicReason=Xe;exports.isAppScheduleTimeoutMs=be;exports.isSkillBackendEnv=Wn;exports.openInheritedAppJobTransport=fn;exports.parseAppJobChannel=ke;exports.parseAppJobControlReply=Ne;exports.parseAppJobControlRequest=ct;exports.parseAppJobRunPush=xe;exports.parseAppJobRunReport=ft;exports.parseAppJobView=bt;exports.readAppContext=Re;exports.readAppJobChannel=je;exports.runAppEntry=Nt;exports.runSkillApp=Tt;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,67 @@
1
+ import { type AppJobOperation, type AppJobRefusalCode, type AppJobStopReason } from './job-contract.js';
2
+ import { type AppJobChannel, type AppJobView, type AppJobWireHandle } from './job-wire.js';
3
+ export interface AppJobLineTransport {
4
+ write(line: string): void;
5
+ drain(): Promise<void>;
6
+ onData(listener: (chunk: string) => void): void;
7
+ onEnd(listener: () => void): void;
8
+ close(): void;
9
+ }
10
+ export type AppJobTransportOpener = (fd: number) => AppJobLineTransport;
11
+ export interface AppJobBridgeOptions {
12
+ readonly channel: AppJobChannel;
13
+ readonly open?: AppJobTransportOpener;
14
+ readonly replyTimeoutMs?: number;
15
+ }
16
+ export type AppJobStartOutcome = {
17
+ readonly kind: 'started' | 'attached';
18
+ readonly job: AppJobView;
19
+ } | {
20
+ readonly kind: 'refused';
21
+ readonly code: AppJobRefusalCode;
22
+ };
23
+ export type AppJobStatusOutcome = {
24
+ readonly kind: 'status';
25
+ readonly job: AppJobView | null;
26
+ } | {
27
+ readonly kind: 'refused';
28
+ readonly code: AppJobRefusalCode;
29
+ };
30
+ export type AppJobStopOutcome = {
31
+ readonly kind: 'stopping';
32
+ readonly job: AppJobView;
33
+ } | {
34
+ readonly kind: 'refused';
35
+ readonly code: AppJobRefusalCode;
36
+ };
37
+ export interface AppJobs {
38
+ readonly granted: readonly AppJobOperation[];
39
+ start(): Promise<AppJobStartOutcome>;
40
+ status(handle?: AppJobWireHandle): Promise<AppJobStatusOutcome>;
41
+ cancel(handle: AppJobWireHandle): Promise<AppJobStopOutcome>;
42
+ }
43
+ export interface AppJobProgress {
44
+ readonly phase: string;
45
+ readonly completed?: number;
46
+ readonly total?: number;
47
+ readonly resumable?: boolean;
48
+ }
49
+ export interface AppJobRun {
50
+ readonly handle: AppJobWireHandle;
51
+ readonly stopRequested: boolean;
52
+ readonly stopReason: AppJobStopReason | null;
53
+ progress(report: AppJobProgress): void;
54
+ heartbeat(): void;
55
+ complete(): void;
56
+ fail(code: string, recoverable: boolean): void;
57
+ onStop(listener: (reason: AppJobStopReason) => void): () => void;
58
+ }
59
+ export declare class AppJobBridge {
60
+ #private;
61
+ constructor(options: AppJobBridgeOptions);
62
+ jobsFor(declared: readonly AppJobOperation[] | undefined): AppJobs | undefined;
63
+ runFor(isDeclaredJob: boolean): AppJobRun | undefined;
64
+ close(): void;
65
+ drain(timeoutMs?: number): Promise<void>;
66
+ }
67
+ export declare function openInheritedAppJobTransport(fd: number): AppJobLineTransport;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ import { CrewXApp, type AppDefinition, type JsonObject } from './index.js';
2
+ export declare const CODE_MAP_EXAMPLE_DEFINITION: AppDefinition;
3
+ export declare class CodeMapJobExample extends CrewXApp {
4
+ static definition: AppDefinition;
5
+ emptyState(): JsonObject;
6
+ analyze(): Promise<JsonObject>;
7
+ status(): Promise<JsonObject>;
8
+ cancel(): Promise<JsonObject>;
9
+ autoAnalyze(): Promise<JsonObject>;
10
+ analyzeRun(): Promise<JsonObject>;
11
+ }
@@ -0,0 +1,40 @@
1
+ export declare const APP_JOB_DEADLINE_MS: Readonly<{
2
+ min: 60000;
3
+ max: 1800000;
4
+ default: 600000;
5
+ }>;
6
+ export declare const APP_JOB_STOP_GRACE_MS: Readonly<{
7
+ min: 1000;
8
+ max: 120000;
9
+ default: 30000;
10
+ }>;
11
+ export declare const APP_JOB_MAX_PER_APP = 1;
12
+ export declare const APP_JOB_CAPABILITY = "crewx/appJobs";
13
+ export declare const APP_JOB_CAPABILITY_VERSION = 1;
14
+ export declare const APP_JOB_STATES: readonly ["starting", "running", "stopping", "finished"];
15
+ export type AppJobState = (typeof APP_JOB_STATES)[number];
16
+ export declare const APP_JOB_OUTCOMES: readonly ["succeeded", "failed", "timed_out", "cancelled", "shutdown", "interrupted"];
17
+ export type AppJobOutcome = (typeof APP_JOB_OUTCOMES)[number];
18
+ export declare const APP_JOB_STOP_REASONS: readonly ["cancelled", "timed_out", "shutdown"];
19
+ export type AppJobStopReason = (typeof APP_JOB_STOP_REASONS)[number];
20
+ export declare const APP_JOB_TRIGGERS: readonly ["manual", "schedule"];
21
+ export type AppJobTrigger = (typeof APP_JOB_TRIGGERS)[number];
22
+ export declare const APP_JOB_PHASE_PATTERN: RegExp;
23
+ export declare const APP_JOB_CODE_PATTERN: RegExp;
24
+ export declare const APP_JOB_OPERATIONS: readonly ["start", "status", "cancel"];
25
+ export type AppJobOperation = (typeof APP_JOB_OPERATIONS)[number];
26
+ export declare const APP_JOB_REFUSAL_CODES: readonly ["APP_JOB_NOT_DECLARED", "APP_JOB_NOT_AUTHORIZED", "APP_JOB_SELF_START", "APP_JOB_OWNER_INVALID", "APP_JOB_DEFINITION_INVALID", "APP_JOB_DEFINITION_CHANGED", "APP_JOB_DEADLINE_INVALID", "APP_JOB_SHUTTING_DOWN", "APP_JOB_OWNER_MISMATCH", "APP_JOB_STALE_HANDLE", "APP_JOB_NOT_ACTIVE", "APP_JOB_NOT_GRANTED"];
27
+ export type AppJobRefusalCode = (typeof APP_JOB_REFUSAL_CODES)[number];
28
+ export declare const APP_JOB_RUN_REQUIRED: "APP_JOB_RUN_REQUIRED";
29
+ export interface ToolJobDeclaration {
30
+ readonly deadlineMs?: number;
31
+ }
32
+ export declare function isAppJobDeadlineMs(value: unknown): value is number;
33
+ export declare function isAppJobCode(value: unknown): value is string;
34
+ export declare function isAppJobPhase(value: unknown): value is string;
35
+ export declare function isAppJobOperation(value: unknown): value is AppJobOperation;
36
+ export interface AppJobCapabilityDeclaration {
37
+ readonly name: string;
38
+ readonly version: number;
39
+ }
40
+ export declare function hasAppJobCapability(advertised: readonly AppJobCapabilityDeclaration[] | undefined): boolean;
@@ -0,0 +1,149 @@
1
+ import { type AppJobOperation, type AppJobOutcome, type AppJobRefusalCode, type AppJobState, type AppJobStopReason, type AppJobTrigger } from './job-contract.js';
2
+ export declare const APP_JOB_BRIDGE_ENV = "CREWX_APP_JOB_CHANNEL";
3
+ export declare const APP_JOB_BRIDGE_VERSION = 1;
4
+ export declare const APP_JOB_BRIDGE_MAX_LINE_BYTES = 4096;
5
+ export declare const APP_JOB_BRIDGE_REPLY_TIMEOUT_MS = 10000;
6
+ export declare const APP_JOB_BRIDGE_DRAIN_TIMEOUT_MS = 5000;
7
+ export declare const APP_JOB_BRIDGE_CHANNEL_MAX_BYTES = 512;
8
+ export declare const APP_JOB_BRIDGE_FD: Readonly<{
9
+ min: 3;
10
+ max: 16;
11
+ }>;
12
+ export declare const APP_JOB_BRIDGE_ERROR_CODES: readonly ["APP_JOB_BRIDGE_UNAVAILABLE", "APP_JOB_BRIDGE_INVALID", "APP_JOB_BRIDGE_TIMEOUT", "APP_JOB_BRIDGE_CLOSED"];
13
+ export type AppJobBridgeErrorCode = (typeof APP_JOB_BRIDGE_ERROR_CODES)[number];
14
+ export interface AppJobWireHandle {
15
+ readonly runId: string;
16
+ readonly generation: number;
17
+ }
18
+ export interface AppJobView {
19
+ readonly handle: AppJobWireHandle;
20
+ readonly state: AppJobState;
21
+ readonly stopReason: AppJobStopReason | null;
22
+ readonly trigger: AppJobTrigger;
23
+ readonly outcome: AppJobOutcome | null;
24
+ readonly phase: string | null;
25
+ readonly completed: number | null;
26
+ readonly total: number | null;
27
+ readonly resumable: boolean;
28
+ readonly lastHeartbeatAt: string | null;
29
+ readonly startedAt: string;
30
+ readonly finishedAt: string | null;
31
+ readonly errorCode: string | null;
32
+ readonly recoverable: boolean | null;
33
+ }
34
+ export type AppJobChannel = {
35
+ readonly v: 1;
36
+ readonly role: 'control';
37
+ readonly fd: number;
38
+ readonly operations: readonly AppJobOperation[];
39
+ } | {
40
+ readonly v: 1;
41
+ readonly role: 'run';
42
+ readonly fd: number;
43
+ readonly runId: string;
44
+ readonly generation: number;
45
+ };
46
+ export type AppJobControlRequest = {
47
+ readonly v: 1;
48
+ readonly op: 'start';
49
+ readonly requestId: string;
50
+ readonly seq: number;
51
+ } | {
52
+ readonly v: 1;
53
+ readonly op: 'status';
54
+ readonly requestId: string;
55
+ readonly seq: number;
56
+ readonly handle?: AppJobWireHandle;
57
+ } | {
58
+ readonly v: 1;
59
+ readonly op: 'cancel';
60
+ readonly requestId: string;
61
+ readonly seq: number;
62
+ readonly handle: AppJobWireHandle;
63
+ };
64
+ export type AppJobControlReply = {
65
+ readonly v: 1;
66
+ readonly requestId: string;
67
+ readonly seq: number;
68
+ readonly ok: true;
69
+ readonly op: 'start';
70
+ readonly outcome: 'started' | 'attached';
71
+ readonly job: AppJobView;
72
+ } | {
73
+ readonly v: 1;
74
+ readonly requestId: string;
75
+ readonly seq: number;
76
+ readonly ok: true;
77
+ readonly op: 'status';
78
+ readonly job: AppJobView | null;
79
+ } | {
80
+ readonly v: 1;
81
+ readonly requestId: string;
82
+ readonly seq: number;
83
+ readonly ok: true;
84
+ readonly op: 'cancel';
85
+ readonly outcome: 'stopping';
86
+ readonly job: AppJobView;
87
+ } | {
88
+ readonly v: 1;
89
+ readonly requestId: string;
90
+ readonly seq: number;
91
+ readonly ok: false;
92
+ readonly code: AppJobRefusalCode;
93
+ };
94
+ export type AppJobRunReport = {
95
+ readonly v: 1;
96
+ readonly kind: 'heartbeat';
97
+ readonly runId: string;
98
+ readonly generation: number;
99
+ } | {
100
+ readonly v: 1;
101
+ readonly kind: 'progress';
102
+ readonly runId: string;
103
+ readonly generation: number;
104
+ readonly phase: string;
105
+ readonly completed?: number;
106
+ readonly total?: number;
107
+ readonly resumable?: boolean;
108
+ } | {
109
+ readonly v: 1;
110
+ readonly kind: 'completed';
111
+ readonly runId: string;
112
+ readonly generation: number;
113
+ } | {
114
+ readonly v: 1;
115
+ readonly kind: 'failed';
116
+ readonly runId: string;
117
+ readonly generation: number;
118
+ readonly code: string;
119
+ readonly recoverable: boolean;
120
+ };
121
+ export interface AppJobRunPush {
122
+ readonly v: 1;
123
+ readonly kind: 'stop';
124
+ readonly runId: string;
125
+ readonly generation: number;
126
+ readonly reason: AppJobStopReason;
127
+ }
128
+ export type AppJobLineEvent = {
129
+ readonly kind: 'line';
130
+ readonly line: string;
131
+ } | {
132
+ readonly kind: 'oversized';
133
+ };
134
+ export declare class AppJobLineReader {
135
+ #private;
136
+ push(chunk: string): AppJobLineEvent[];
137
+ }
138
+ export declare function encodeAppJobLine(message: object): string;
139
+ export declare function parseAppJobControlRequest(line: string): AppJobControlRequest | undefined;
140
+ export declare function parseAppJobControlReply(line: string): AppJobControlReply | undefined;
141
+ export declare function parseAppJobRunReport(line: string): AppJobRunReport | undefined;
142
+ export declare function parseAppJobRunPush(line: string): AppJobRunPush | undefined;
143
+ export declare function parseAppJobChannel(value: unknown): AppJobChannel | undefined;
144
+ export declare function readAppJobChannel(env: Readonly<Record<string, string | undefined>>): AppJobChannel | undefined;
145
+ export declare function buildAppJobChannelEnvironment(channel: AppJobChannel): {
146
+ readonly CREWX_APP_JOB_CHANNEL: string;
147
+ };
148
+ export declare function appJobTriggerForActor(actorKind: 'user' | 'agent' | 'schedule'): AppJobTrigger;
149
+ export declare function parseAppJobView(value: unknown): AppJobView | undefined;
@@ -1,4 +1,5 @@
1
1
  import { type AppContext, type AppFailureOutcome, type CrewXAppConstructor, type JsonObject } from './app.js';
2
+ import { type AppJobBridgeOptions } from './job-bridge.js';
2
3
  export interface AppFailureInfo {
3
4
  readonly outcome: AppFailureOutcome;
4
5
  readonly detail: string | null;
@@ -16,6 +17,7 @@ export interface RunSkillAppOptions {
16
17
  readonly onFailure?: (errorCode: string, error?: unknown, info?: AppFailureInfo) => void;
17
18
  readonly consoleManaged?: boolean;
18
19
  readonly context?: AppContext;
20
+ readonly jobBridge?: AppJobBridgeOptions | null;
19
21
  }
20
22
  export declare function executeAppRequest(appClass: CrewXAppConstructor, rawRequest: unknown, workspaceRoot?: string, context?: AppContext): Promise<JsonObject>;
21
23
  export declare function runSkillApp(appClass: CrewXAppConstructor, options?: RunSkillAppOptions): Promise<void>;
@@ -0,0 +1,2 @@
1
+ import { type AppRuntimeReferenceInput, type AppRuntimeReferenceResult } from './contract.js';
2
+ export declare function checkAppRuntimeReferences(input: AppRuntimeReferenceInput): AppRuntimeReferenceResult;
@@ -0,0 +1,54 @@
1
+ export declare const APP_RUNTIME_POLICY_VERSION = "app-runtime-references/1";
2
+ export declare const APP_RUNTIME_REFUSAL_CODES: readonly ["INPUT_INVALID", "LIMIT_EXCEEDED", "PARSE_FAILED", "UNSUPPORTED_LOADER", "BINDING_AMBIGUOUS", "TARGET_OUTSIDE_CLOSURE", "BARE_SPECIFIER", "BUILTIN_NOT_SELECTED", "WORKER_UNSUPPORTED"];
3
+ export type AppRuntimeRefusalCode = (typeof APP_RUNTIME_REFUSAL_CODES)[number];
4
+ export declare const APP_RUNTIME_LIMITS: {
5
+ readonly maxSourceBytesPerArtifact: number;
6
+ readonly maxSourceBytesTotal: number;
7
+ readonly maxExecutableArtifacts: 512;
8
+ readonly maxAstNodesPerArtifact: 1500000;
9
+ readonly maxAstNodesTotal: 2000000;
10
+ readonly maxNestingDepth: 512;
11
+ readonly maxClosurePaths: 4096;
12
+ readonly maxBuiltinSelections: 256;
13
+ readonly maxMetadataBytes: number;
14
+ readonly maxPathLength: 1024;
15
+ readonly maxBuiltinNameLength: 256;
16
+ };
17
+ export type AppArtifactKind = 'esm' | 'commonjs';
18
+ export interface AppRuntimeArtifact {
19
+ readonly path: string;
20
+ readonly kind: AppArtifactKind;
21
+ readonly source: string;
22
+ }
23
+ export interface AppRuntimeReferenceInput {
24
+ readonly artifacts: readonly AppRuntimeArtifact[];
25
+ readonly closurePaths: readonly string[];
26
+ readonly builtins: readonly string[];
27
+ }
28
+ export interface AppRuntimeLocation {
29
+ readonly offset: number;
30
+ readonly line: number;
31
+ readonly column: number;
32
+ }
33
+ export type AppRuntimeReferenceKind = 'import' | 'reexport' | 'dynamic-import' | 'url-import' | 'require' | 'worker';
34
+ export type AppRuntimeTarget = {
35
+ readonly path: string;
36
+ } | {
37
+ readonly builtin: string;
38
+ };
39
+ export interface AppRuntimeReference {
40
+ readonly from: string;
41
+ readonly kind: AppRuntimeReferenceKind;
42
+ readonly target: AppRuntimeTarget;
43
+ readonly loc: AppRuntimeLocation;
44
+ }
45
+ export type AppRuntimeReferenceResult = {
46
+ readonly ok: true;
47
+ readonly references: readonly AppRuntimeReference[];
48
+ } | {
49
+ readonly ok: false;
50
+ readonly code: AppRuntimeRefusalCode;
51
+ readonly path: string;
52
+ readonly loc?: AppRuntimeLocation;
53
+ readonly detail: string;
54
+ };
@@ -0,0 +1,15 @@
1
+ import { type Ast } from './scan.js';
2
+ export interface BannerMatch {
3
+ readonly importDeclaration: Ast;
4
+ readonly importLocal: Ast;
5
+ readonly calleeNode: Ast;
6
+ readonly requireId: Ast;
7
+ }
8
+ export interface HelperMatch {
9
+ readonly bindingId: Ast;
10
+ readonly start: number;
11
+ readonly end: number;
12
+ }
13
+ export declare function matchBanner(body: readonly unknown[]): BannerMatch | undefined;
14
+ export declare function matchHelper(body: readonly unknown[]): HelperMatch | undefined;
15
+ export declare function isImportMetaUrl(value: unknown): value is Ast;
@@ -0,0 +1,3 @@
1
+ export { checkAppRuntimeReferences } from './check.js';
2
+ export { APP_RUNTIME_LIMITS, APP_RUNTIME_POLICY_VERSION, APP_RUNTIME_REFUSAL_CODES } from './contract.js';
3
+ export type { AppArtifactKind, AppRuntimeArtifact, AppRuntimeLocation, AppRuntimeReference, AppRuntimeReferenceInput, AppRuntimeReferenceKind, AppRuntimeReferenceResult, AppRuntimeRefusalCode, AppRuntimeTarget, } from './contract.js';