@1agents/acp-service 0.9.0 → 0.9.1
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/README.md +19 -13
- package/dist/bin/a2a.js +6 -2
- package/dist/bin/acp-service.js +24 -0
- package/dist/bin/process.d.ts +4 -0
- package/dist/bin/process.js +57 -0
- package/dist/bin/rsi.d.ts +3 -0
- package/dist/bin/rsi.js +114 -0
- package/dist/bin/ticket.d.ts +13 -0
- package/dist/bin/ticket.js +97 -0
- package/dist/bin/trail.d.ts +4 -0
- package/dist/bin/trail.js +62 -0
- package/dist/src/a2a/artifact-content.d.ts +9 -0
- package/dist/src/a2a/artifact-content.js +45 -0
- package/dist/src/a2a/desktop-notify.d.ts +1 -0
- package/dist/src/a2a/desktop-notify.js +12 -0
- package/dist/src/a2a/execution-binding.d.ts +9 -0
- package/dist/src/a2a/execution-binding.js +19 -0
- package/dist/src/a2a/executor.d.ts +6 -0
- package/dist/src/a2a/executor.js +112 -12
- package/dist/src/a2a/gateway.d.ts +537 -2
- package/dist/src/a2a/gateway.js +1014 -87
- package/dist/src/a2a/index.d.ts +8 -1
- package/dist/src/a2a/index.js +4 -0
- package/dist/src/a2a/job-directory.d.ts +6 -0
- package/dist/src/a2a/job-directory.js +19 -0
- package/dist/src/a2a/preflight.js +16 -1
- package/dist/src/a2a/resubmit.d.ts +46 -0
- package/dist/src/a2a/resubmit.js +82 -0
- package/dist/src/a2a/result-metadata.d.ts +3 -0
- package/dist/src/a2a/result-metadata.js +23 -5
- package/dist/src/a2a/server.d.ts +10 -0
- package/dist/src/a2a/server.js +125 -1
- package/dist/src/a2a/session-lifecycle.d.ts +40 -0
- package/dist/src/a2a/session-lifecycle.js +54 -0
- package/dist/src/a2a/store.d.ts +4 -0
- package/dist/src/a2a/store.js +70 -1
- package/dist/src/a2a/types.d.ts +45 -0
- package/dist/src/a2a/workbench-ui.d.ts +28 -0
- package/dist/src/a2a/workbench-ui.js +182 -0
- package/dist/src/acp-connection.js +27 -3
- package/dist/src/bridge.d.ts +1 -0
- package/dist/src/bridge.js +191 -39
- package/dist/src/capacity-queue.d.ts +35 -0
- package/dist/src/capacity-queue.js +139 -2
- package/dist/src/capacity.d.ts +25 -0
- package/dist/src/capacity.js +48 -9
- package/dist/src/dsh.js +1 -1
- package/dist/src/execution/agent-files.d.ts +25 -0
- package/dist/src/execution/agent-files.js +90 -0
- package/dist/src/execution/agent-registry.d.ts +164 -0
- package/dist/src/execution/agent-registry.js +275 -0
- package/dist/src/execution/human-review.d.ts +2 -0
- package/dist/src/execution/human-review.js +3 -1
- package/dist/src/execution/ledger.d.ts +52 -0
- package/dist/src/execution/ledger.js +83 -5
- package/dist/src/execution/process-request.d.ts +151 -0
- package/dist/src/execution/process-request.js +177 -0
- package/dist/src/execution/targets.d.ts +15 -0
- package/dist/src/execution/targets.js +22 -3
- package/dist/src/execution/ticket-executor.d.ts +25 -0
- package/dist/src/execution/ticket-executor.js +27 -0
- package/dist/src/execution/ticket.d.ts +326 -0
- package/dist/src/execution/ticket.js +301 -0
- package/dist/src/execution/workbench-chat.d.ts +25 -0
- package/dist/src/execution/workbench-chat.js +54 -0
- package/dist/src/execution/workbench.d.ts +32 -1
- package/dist/src/execution/workbench.js +113 -22
- package/dist/src/rsi/gate.d.ts +25 -0
- package/dist/src/rsi/gate.js +59 -0
- package/dist/src/rsi/outline-run.d.ts +107 -0
- package/dist/src/rsi/outline-run.js +443 -0
- package/dist/workbench-ui/app.css +453 -0
- package/dist/workbench-ui/app.js +13 -0
- package/dist/workbench-ui/chunk-23JHGYT3.js +1 -0
- package/dist/workbench-ui/chunk-3H6STGPV.js +1 -0
- package/dist/workbench-ui/chunk-3SNBBMGH.js +1 -0
- package/dist/workbench-ui/chunk-3XJZ6DIE.js +1 -0
- package/dist/workbench-ui/chunk-44KDLLKJ.js +1 -0
- package/dist/workbench-ui/chunk-46H7FU5Y.js +7 -0
- package/dist/workbench-ui/chunk-4N44QPL7.js +1 -0
- package/dist/workbench-ui/chunk-4YN4BS7I.js +1 -0
- package/dist/workbench-ui/chunk-53EG4IVQ.js +96 -0
- package/dist/workbench-ui/chunk-5FIPUNR4.js +1 -0
- package/dist/workbench-ui/chunk-6DWWYA6G.js +2 -0
- package/dist/workbench-ui/chunk-6FU3T633.js +99 -0
- package/dist/workbench-ui/chunk-6XKIHRA4.js +1 -0
- package/dist/workbench-ui/chunk-7GIX43Y5.js +1 -0
- package/dist/workbench-ui/chunk-7Q4WBGX6.js +4 -0
- package/dist/workbench-ui/chunk-A3BQM7HR.js +1 -0
- package/dist/workbench-ui/chunk-AFCFDDOP.js +24 -0
- package/dist/workbench-ui/chunk-AG67EUYD.js +89 -0
- package/dist/workbench-ui/chunk-AGJHMMTN.js +1 -0
- package/dist/workbench-ui/chunk-AO6JUBV6.js +41 -0
- package/dist/workbench-ui/chunk-AUSLTP43.js +72 -0
- package/dist/workbench-ui/chunk-AVZL46TT.js +1 -0
- package/dist/workbench-ui/chunk-AZRIGIV2.js +168 -0
- package/dist/workbench-ui/chunk-B2LIVH37.js +1 -0
- package/dist/workbench-ui/chunk-B7YX5TR5.js +1 -0
- package/dist/workbench-ui/chunk-BCB4X4XX.js +1 -0
- package/dist/workbench-ui/chunk-BCRQUL2A.js +88 -0
- package/dist/workbench-ui/chunk-BI6UHHQP.js +1 -0
- package/dist/workbench-ui/chunk-BLSLQ4AQ.js +120 -0
- package/dist/workbench-ui/chunk-C3QSRS6E.js +1 -0
- package/dist/workbench-ui/chunk-CK7M2PJ3.js +62 -0
- package/dist/workbench-ui/chunk-CM6LZ7TU.js +1 -0
- package/dist/workbench-ui/chunk-CP63H27F.js +36 -0
- package/dist/workbench-ui/chunk-CPUMMIS2.js +70 -0
- package/dist/workbench-ui/chunk-CSEIBI5U.js +2 -0
- package/dist/workbench-ui/chunk-CUS65DKZ.js +161 -0
- package/dist/workbench-ui/chunk-CVQY7TNC.js +1 -0
- package/dist/workbench-ui/chunk-D6S3XBIX.js +106 -0
- package/dist/workbench-ui/chunk-E253Y562.js +1 -0
- package/dist/workbench-ui/chunk-EADDJUDC.js +1 -0
- package/dist/workbench-ui/chunk-EBGJ3YXG.js +206 -0
- package/dist/workbench-ui/chunk-EKPVZ3WY.js +8 -0
- package/dist/workbench-ui/chunk-EQDCEAFY.js +1 -0
- package/dist/workbench-ui/chunk-ES3SSDJY.js +40 -0
- package/dist/workbench-ui/chunk-ESFD2H7N.js +231 -0
- package/dist/workbench-ui/chunk-FVOHPMS6.js +1 -0
- package/dist/workbench-ui/chunk-FXMQAGVT.js +1 -0
- package/dist/workbench-ui/chunk-GGTADRXD.js +24 -0
- package/dist/workbench-ui/chunk-GHIVPGNQ.js +1 -0
- package/dist/workbench-ui/chunk-GLU2YQV2.js +1 -0
- package/dist/workbench-ui/chunk-GOCKBYSM.js +1 -0
- package/dist/workbench-ui/chunk-H2KMMTJB.js +1 -0
- package/dist/workbench-ui/chunk-HGVLDNPP.js +39 -0
- package/dist/workbench-ui/chunk-HSAVC5GY.js +1 -0
- package/dist/workbench-ui/chunk-HSEAD2JH.js +1 -0
- package/dist/workbench-ui/chunk-HSIHOBTY.js +1 -0
- package/dist/workbench-ui/chunk-IZXOKUGG.js +67 -0
- package/dist/workbench-ui/chunk-JFT2LC2T.js +1 -0
- package/dist/workbench-ui/chunk-JHL3ZDYK.js +3 -0
- package/dist/workbench-ui/chunk-JMORLCZG.js +257 -0
- package/dist/workbench-ui/chunk-JR4SIX7A.js +1 -0
- package/dist/workbench-ui/chunk-K23HAGEH.js +30 -0
- package/dist/workbench-ui/chunk-K43JDCBH.js +1 -0
- package/dist/workbench-ui/chunk-KINKFJY7.js +1 -0
- package/dist/workbench-ui/chunk-KKQSA4LI.js +2 -0
- package/dist/workbench-ui/chunk-KOUZX3UX.js +1 -0
- package/dist/workbench-ui/chunk-KR4DRHW2.js +78 -0
- package/dist/workbench-ui/chunk-KT4DJNOR.js +1 -0
- package/dist/workbench-ui/chunk-KTPNKRRZ.js +292 -0
- package/dist/workbench-ui/chunk-LFHIPGSU.js +7 -0
- package/dist/workbench-ui/chunk-LWDL4HZB.js +125 -0
- package/dist/workbench-ui/chunk-MVYC3CY4.js +1 -0
- package/dist/workbench-ui/chunk-NWUPALCY.js +129 -0
- package/dist/workbench-ui/chunk-NY7C662Z.js +1 -0
- package/dist/workbench-ui/chunk-O76WTHWP.js +1 -0
- package/dist/workbench-ui/chunk-OTF7YHRE.js +162 -0
- package/dist/workbench-ui/chunk-P6TKKRKP.js +1 -0
- package/dist/workbench-ui/chunk-PFHOOWV3.js +1 -0
- package/dist/workbench-ui/chunk-PUQLANIM.js +1 -0
- package/dist/workbench-ui/chunk-PZCGBYVO.js +1 -0
- package/dist/workbench-ui/chunk-QOHUZGP4.js +1 -0
- package/dist/workbench-ui/chunk-QSEG3OFF.js +1 -0
- package/dist/workbench-ui/chunk-QYPOXZIA.js +84 -0
- package/dist/workbench-ui/chunk-R6SOF3JC.js +1 -0
- package/dist/workbench-ui/chunk-RCLOYU5F.js +1 -0
- package/dist/workbench-ui/chunk-RSRUP64S.js +1 -0
- package/dist/workbench-ui/chunk-RVAIT6JW.js +1 -0
- package/dist/workbench-ui/chunk-S2CCN3II.js +1 -0
- package/dist/workbench-ui/chunk-S2Q52W46.js +1 -0
- package/dist/workbench-ui/chunk-S2W5THJ5.js +1 -0
- package/dist/workbench-ui/chunk-S6ZQZNOX.js +1 -0
- package/dist/workbench-ui/chunk-S74PLMMS.js +1 -0
- package/dist/workbench-ui/chunk-S7C4HKEY.js +1 -0
- package/dist/workbench-ui/chunk-SDTB3Q65.js +1 -0
- package/dist/workbench-ui/chunk-SLPRGYUV.js +32 -0
- package/dist/workbench-ui/chunk-SQE76S5B.js +1 -0
- package/dist/workbench-ui/chunk-SSDZPVPW.js +1 -0
- package/dist/workbench-ui/chunk-SVI7DGIE.js +1 -0
- package/dist/workbench-ui/chunk-T6QKLZ4H.js +62 -0
- package/dist/workbench-ui/chunk-TJNRPTFL.js +1 -0
- package/dist/workbench-ui/chunk-TP6U4EDH.js +2 -0
- package/dist/workbench-ui/chunk-TYAAT3GQ.js +1 -0
- package/dist/workbench-ui/chunk-U6OCY4ZH.js +1 -0
- package/dist/workbench-ui/chunk-UAN3NLRF.js +1 -0
- package/dist/workbench-ui/chunk-UMLU3FIX.js +1 -0
- package/dist/workbench-ui/chunk-URIY2OTM.js +1 -0
- package/dist/workbench-ui/chunk-V2NUKAA7.js +38 -0
- package/dist/workbench-ui/chunk-V4QLL4TE.js +139 -0
- package/dist/workbench-ui/chunk-VASHXUK4.js +2 -0
- package/dist/workbench-ui/chunk-VJLIWNIU.js +1 -0
- package/dist/workbench-ui/chunk-VQNQFBID.js +1 -0
- package/dist/workbench-ui/chunk-VSIWU7XA.js +3 -0
- package/dist/workbench-ui/chunk-VSJASPUZ.js +321 -0
- package/dist/workbench-ui/chunk-VXPNUNUX.js +3 -0
- package/dist/workbench-ui/chunk-WBKLDCV6.js +1 -0
- package/dist/workbench-ui/chunk-WOKJM3FY.js +1 -0
- package/dist/workbench-ui/chunk-X3U3NA3X.js +34 -0
- package/dist/workbench-ui/chunk-XBYU7M4J.js +1 -0
- package/dist/workbench-ui/chunk-XBZAO4ID.js +10 -0
- package/dist/workbench-ui/chunk-XLLPZ2WO.js +1 -0
- package/dist/workbench-ui/chunk-YFVL4NJL.js +1 -0
- package/dist/workbench-ui/chunk-YRFQENM4.js +1 -0
- package/dist/workbench-ui/chunk-YUADQVB2.js +1 -0
- package/dist/workbench-ui/chunk-Z3TCAKM5.js +1 -0
- package/dist/workbench-ui/chunk-Z6QR6FRE.js +10 -0
- package/dist/workbench-ui/chunk-ZJPSORPP.js +3 -0
- package/dist/workbench-ui/chunk-ZLGCSTR2.js +15 -0
- package/dist/workbench-ui/chunk-ZLR4SG5X.js +1 -0
- package/dist/workbench-ui/chunk-ZND3TTGF.js +1 -0
- package/dist/workbench-ui/chunk-ZOP3ZYH7.js +2 -0
- package/dist/workbench-ui/index.html +14 -0
- package/package.json +19 -8
- package/skills/acp-service/SKILL.md +3 -1
- package/skills/acp-service/references/a2a.md +17 -5
- package/skills/acp-service/references/dsh.md +2 -0
- package/skills/acp-service/references/roles-and-tasks.md +1 -1
- package/skills/rsi-coach/SKILL.md +134 -0
- package/vendor/dsh/README.md +10 -6
- package/vendor/dsh/a2a-executor.d.ts +56 -2
- package/vendor/dsh/a2a-executor.js +163 -17
- package/vendor/dsh/a2a.d.ts +12 -2
- package/vendor/dsh/a2a.js +9 -2
- package/vendor/dsh/adapter.d.ts +52 -3
- package/vendor/dsh/adapter.js +297 -30
- package/vendor/dsh/client.js +67 -11
- package/vendor/dsh/index.js +55 -3
- package/vendor/dsh/native-approvals.d.ts +4 -0
- package/vendor/dsh/native-approvals.js +44 -0
- package/vendor/dsh/preset-route.d.ts +49 -0
- package/vendor/dsh/preset-route.js +51 -0
- package/vendor/dsh/preset.js +10 -3
- package/vendor/dsh/process-admission.d.ts +25 -0
- package/vendor/dsh/process-admission.js +87 -0
- package/vendor/dsh/process-requests.d.ts +57 -0
- package/vendor/dsh/process-requests.js +49 -0
- package/vendor/dsh/review-mcp.d.ts +1 -0
- package/vendor/dsh/review-mcp.js +56 -0
- package/vendor/dsh/review.d.ts +30 -0
- package/vendor/dsh/review.js +149 -0
- package/vendor/dsh/session-settings.d.ts +34 -0
- package/vendor/dsh/session-settings.js +114 -0
- package/vendor/dsh/ticket-spec.d.ts +30 -0
- package/vendor/dsh/ticket-spec.js +10 -0
- package/vendor/dsh/ticket-tools.d.ts +21 -0
- package/vendor/dsh/ticket-tools.js +43 -0
- package/vendor/dsh/workbench.d.ts +18 -0
- package/vendor/dsh/workbench.js +91 -0
- package/vendor/runtime/README.md +6 -4
- package/vendor/runtime/dist/docs-site/CLI.html +2 -2
- package/vendor/runtime/dist/docs-site/VISION.html +2 -2
- package/vendor/runtime/dist/docs-site/agents.html +2 -2
- package/vendor/runtime/dist/docs-site/compare.html +2 -2
- package/vendor/runtime/dist/docs-site/config.html +2 -2
- package/vendor/runtime/dist/docs-site/custom-agents.html +2 -2
- package/vendor/runtime/dist/docs-site/exit-codes.html +2 -2
- package/vendor/runtime/dist/docs-site/flows.html +2 -2
- package/vendor/runtime/dist/docs-site/index.html +1 -1
- package/vendor/runtime/dist/docs-site/install.html +2 -2
- package/vendor/runtime/dist/docs-site/llms.txt +1 -1
- package/vendor/runtime/dist/docs-site/output-formats.html +2 -2
- package/vendor/runtime/dist/docs-site/permissions.html +2 -2
- package/vendor/runtime/dist/docs-site/prompting.html +2 -2
- package/vendor/runtime/dist/docs-site/quickstart.html +2 -2
- package/vendor/runtime/dist/docs-site/releasing.html +2 -2
- package/vendor/runtime/dist/docs-site/runtime-environment.html +2 -2
- package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +2 -2
- package/vendor/runtime/dist/docs-site/safe-errors.html +2 -2
- package/vendor/runtime/dist/docs-site/session-control.html +2 -2
- package/vendor/runtime/dist/docs-site/session-watch.html +2 -2
- package/vendor/runtime/dist/docs-site/sessions.html +2 -2
- package/vendor/runtime/dist/docs-site/shared-sessions.html +2 -2
- package/vendor/runtime/package.json +6 -4
- package/vendor/runtime/skills/acpx/SKILL.md +2 -0
package/dist/src/bridge.js
CHANGED
|
@@ -87,19 +87,54 @@ let capacityLaunchAbort = new AbortController();
|
|
|
87
87
|
const sessionLaunchControllers = new Map();
|
|
88
88
|
const initializingSessionControllers = new Map();
|
|
89
89
|
const capacityLaunchSignals = new Map();
|
|
90
|
+
// A probed process lease is held before ensureSession. onBeforeSpawn must
|
|
91
|
+
// consume that lease instead of acquiring a second slot. launchId !== capacityId.
|
|
92
|
+
const preparedProcessLeases = new Map();
|
|
93
|
+
const preparedByLaunch = new Map();
|
|
94
|
+
const preparedLaunches = new Set();
|
|
95
|
+
const handshakeTimers = new Map();
|
|
96
|
+
function handshakeMs() {
|
|
97
|
+
const value = Number(process.env.ACP_HANDSHAKE_TIMEOUT_MS);
|
|
98
|
+
return Number.isFinite(value) && value > 0 ? value : 60_000;
|
|
99
|
+
}
|
|
100
|
+
// How long a permission, question or plan prompt waits for a person. The A2A
|
|
101
|
+
// workbench deadline (workbench.requestTimeoutMinutes) must not be longer.
|
|
102
|
+
function interactionTimeoutMs() {
|
|
103
|
+
const value = Number(process.env.ACP_INTERACTION_TIMEOUT_MS);
|
|
104
|
+
return Number.isFinite(value) && value > 0 ? value : 5 * 60 * 1000;
|
|
105
|
+
}
|
|
106
|
+
function interactionTimeoutText() {
|
|
107
|
+
return `${Math.round(interactionTimeoutMs() / 60_000)}min`;
|
|
108
|
+
}
|
|
109
|
+
function clearHandshake(launchId) {
|
|
110
|
+
const timer = handshakeTimers.get(launchId);
|
|
111
|
+
if (timer)
|
|
112
|
+
clearTimeout(timer);
|
|
113
|
+
handshakeTimers.delete(launchId);
|
|
114
|
+
preparedLaunches.delete(launchId);
|
|
115
|
+
preparedByLaunch.delete(launchId);
|
|
116
|
+
}
|
|
117
|
+
const launchOrigins = new Map();
|
|
90
118
|
const capacityLifecycle = createCapacityLifecycle({
|
|
91
|
-
acquire: request =>
|
|
92
|
-
|
|
93
|
-
|
|
119
|
+
acquire: request => {
|
|
120
|
+
const prepared = preparedByLaunch.get(request.id);
|
|
121
|
+
if (prepared)
|
|
122
|
+
return prepared;
|
|
123
|
+
const origin = launchOrigins.get(request.id);
|
|
124
|
+
return processCapacity.acquire(origin ? { ...request, origin } : request, {
|
|
125
|
+
signal: capacityLaunchSignals.get(request.id) || capacityLaunchAbort.signal,
|
|
126
|
+
});
|
|
127
|
+
},
|
|
94
128
|
});
|
|
129
|
+
/** Runtime session key -> the MCP servers its ensure_session asked for. */
|
|
130
|
+
const sessionMcpServers = new Map();
|
|
95
131
|
const runtime = createAcpRuntime({
|
|
96
132
|
// Includes compatibility checks, probes and pre-warm launches. Native user
|
|
97
133
|
// processes outside this service are not admitted through this governor.
|
|
98
134
|
processLifecycle: {
|
|
99
135
|
async onBeforeSpawn(launch) {
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
: undefined;
|
|
136
|
+
const sessionKey = launch.scope.kind === "runtime-session" ? launch.scope.sessionKey : undefined;
|
|
137
|
+
const session = sessionKey ? sessionLaunchControllers.get(sessionKey) : undefined;
|
|
103
138
|
// Capture the generation before the lifecycle's deferred acquire runs.
|
|
104
139
|
const signal = AbortSignal.any([
|
|
105
140
|
capacityLaunchAbort.signal,
|
|
@@ -107,25 +142,54 @@ const runtime = createAcpRuntime({
|
|
|
107
142
|
]);
|
|
108
143
|
capacityLaunchSignals.set(launch.launchId, signal);
|
|
109
144
|
signal.throwIfAborted();
|
|
145
|
+
if (sessionKey && preparedProcessLeases.has(sessionKey)) {
|
|
146
|
+
const lease = preparedProcessLeases.get(sessionKey);
|
|
147
|
+
preparedProcessLeases.delete(sessionKey);
|
|
148
|
+
preparedByLaunch.set(launch.launchId, Promise.resolve(lease));
|
|
149
|
+
preparedLaunches.add(launch.launchId);
|
|
150
|
+
}
|
|
151
|
+
const origin = typeof sessionKey === "string" && sessionKey.startsWith("prewarm_grok_")
|
|
152
|
+
? "prewarm"
|
|
153
|
+
: typeof sessionKey === "string" && sessionKey ? "user-opened" : undefined;
|
|
154
|
+
if (origin)
|
|
155
|
+
launchOrigins.set(launch.launchId, origin);
|
|
110
156
|
await capacityLifecycle.onBeforeSpawn(launch);
|
|
111
157
|
signal.throwIfAborted();
|
|
158
|
+
// The 60s budget starts only after the process slot is held.
|
|
159
|
+
if (preparedLaunches.has(launch.launchId)) {
|
|
160
|
+
const timer = setTimeout(() => {
|
|
161
|
+
if (!preparedLaunches.has(launch.launchId))
|
|
162
|
+
return;
|
|
163
|
+
const current = sessionKey ? sessionLaunchControllers.get(sessionKey) : undefined;
|
|
164
|
+
current?.controller.abort(new Error("ACP handshake timed out"));
|
|
165
|
+
}, handshakeMs());
|
|
166
|
+
timer.unref?.();
|
|
167
|
+
handshakeTimers.set(launch.launchId, timer);
|
|
168
|
+
}
|
|
112
169
|
},
|
|
113
170
|
async onSpawned(started) {
|
|
171
|
+
clearHandshake(started.launchId);
|
|
114
172
|
await capacityLifecycle.onSpawned(started);
|
|
115
173
|
capacityLaunchSignals.delete(started.launchId);
|
|
174
|
+
launchOrigins.delete(started.launchId);
|
|
116
175
|
},
|
|
117
176
|
onSpawnFailed(failure) {
|
|
177
|
+
clearHandshake(failure.launchId);
|
|
118
178
|
capacityLaunchSignals.delete(failure.launchId);
|
|
179
|
+
launchOrigins.delete(failure.launchId);
|
|
119
180
|
return capacityLifecycle.onSpawnFailed(failure);
|
|
120
181
|
},
|
|
121
182
|
onExit(exit) {
|
|
183
|
+
clearHandshake(exit.launchId);
|
|
122
184
|
capacityLaunchSignals.delete(exit.launchId);
|
|
185
|
+
launchOrigins.delete(exit.launchId);
|
|
123
186
|
return capacityLifecycle.onExit(exit);
|
|
124
187
|
},
|
|
125
188
|
},
|
|
126
189
|
cwd: process.cwd(),
|
|
127
190
|
sessionStore: createRuntimeStore({ stateDir: DEFAULT_STATE_DIR }),
|
|
128
191
|
agentRegistry: createServiceAgentRegistry(),
|
|
192
|
+
mcpServers: ({ sessionKey }) => sessionMcpServers.get(sessionKey) ?? [],
|
|
129
193
|
permissionMode: "approve-reads", // default, will be overridden by session or client options
|
|
130
194
|
onPermissionRequest: handlePermissionRequestCallback,
|
|
131
195
|
onAskUserQuestion: handleAskUserQuestionCallback,
|
|
@@ -186,6 +250,8 @@ const turnJournal = createTurnJournal({ stateDir: DEFAULT_STATE_DIR });
|
|
|
186
250
|
// sessionId -> { handle, activeTurn }
|
|
187
251
|
const activeSessions = new Map();
|
|
188
252
|
// Phase 2 Pre-warm pool for grok-build (scoped to the most recent CWD)
|
|
253
|
+
// Disabled: nothing schedules prewarmGrokSession. A spare starts without the
|
|
254
|
+
// session's env, so adopting one silently dropped settings such as GROK_HOME.
|
|
189
255
|
let prewarmedGrokHandle = null;
|
|
190
256
|
let prewarmedGrokCwd = null;
|
|
191
257
|
let lastUsedCwd = process.cwd();
|
|
@@ -253,6 +319,29 @@ async function cancelInitializingSession(sessionId, expectedSignal) {
|
|
|
253
319
|
await initialization.done;
|
|
254
320
|
return true;
|
|
255
321
|
}
|
|
322
|
+
/**
|
|
323
|
+
* Close confirmation: the agent process recorded before close is gone and no process lease
|
|
324
|
+
* still names it. An unknown pid or a lease that outlives the wait stays unconfirmed.
|
|
325
|
+
*/
|
|
326
|
+
async function confirmProcessReleased(pid, timeoutMs = 5_000) {
|
|
327
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
328
|
+
return false;
|
|
329
|
+
const deadline = Date.now() + timeoutMs;
|
|
330
|
+
for (;;) {
|
|
331
|
+
let alive = true;
|
|
332
|
+
try {
|
|
333
|
+
process.kill(pid, 0);
|
|
334
|
+
}
|
|
335
|
+
catch (err) {
|
|
336
|
+
alive = err?.code === "EPERM";
|
|
337
|
+
}
|
|
338
|
+
if (!alive && !(await processCapacity.holdsChild(pid)))
|
|
339
|
+
return true;
|
|
340
|
+
if (Date.now() >= deadline)
|
|
341
|
+
return false;
|
|
342
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
343
|
+
}
|
|
344
|
+
}
|
|
256
345
|
// Map of Agent UUID -> Client Session ID (for permission callbacks)
|
|
257
346
|
const agentSessionToClientSession = new Map();
|
|
258
347
|
function registerAgentSessionMapping(sessionId, handle) {
|
|
@@ -1193,12 +1282,7 @@ export async function dispatchCommand(ws, payload) {
|
|
|
1193
1282
|
// client supplying extra context wants.
|
|
1194
1283
|
sessionOptions.systemPrompt = { append: systemContext };
|
|
1195
1284
|
}
|
|
1196
|
-
|
|
1197
|
-
// project-locked task tools). Merged with runtime-level servers in
|
|
1198
|
-
// the engine; only applies when this session's client is created.
|
|
1199
|
-
if (Array.isArray(mcpServers) && mcpServers.length > 0) {
|
|
1200
|
-
sessionOptions.mcpServers = mcpServers;
|
|
1201
|
-
}
|
|
1285
|
+
const hasMcpServers = Array.isArray(mcpServers) && mcpServers.length > 0;
|
|
1202
1286
|
if (env && typeof env === "object" && !Array.isArray(env)) {
|
|
1203
1287
|
const safeEnv = Object.fromEntries(Object.entries(env).filter(([key, value]) => typeof key === "string" && typeof value === "string"));
|
|
1204
1288
|
if (Object.keys(safeEnv).length > 0) {
|
|
@@ -1262,6 +1346,13 @@ export async function dispatchCommand(ws, payload) {
|
|
|
1262
1346
|
const runtimeSessionKey = profileId
|
|
1263
1347
|
? `${sessionId}@${profileId}-r${profileRevision}`
|
|
1264
1348
|
: (payload.runtimeSessionKey || sessionId);
|
|
1349
|
+
// Per-session MCP servers (e.g. the DSH hand-back and ticket tools). The engine ignores
|
|
1350
|
+
// sessionOptions.mcpServers and reads only the runtime-level option, which looks them up
|
|
1351
|
+
// here by session key whenever it creates this session's client.
|
|
1352
|
+
if (hasMcpServers)
|
|
1353
|
+
sessionMcpServers.set(runtimeSessionKey, mcpServers);
|
|
1354
|
+
else
|
|
1355
|
+
sessionMcpServers.delete(runtimeSessionKey);
|
|
1265
1356
|
// Prefer the explicit resumeSessionId (the agent-side UUID
|
|
1266
1357
|
// recorded in the 1agents index); fall back to acpSessionId
|
|
1267
1358
|
// for older clients. Empty string means "start a fresh session".
|
|
@@ -1400,19 +1491,25 @@ export async function dispatchCommand(ws, payload) {
|
|
|
1400
1491
|
lastUsedCwd = normalizedPath;
|
|
1401
1492
|
}
|
|
1402
1493
|
// Phase 2: Instant pre-warm hit for fresh grok-build sessions if CWD matches!
|
|
1403
|
-
|
|
1494
|
+
// The spare was created without this session's MCP servers, so such a session starts its own process.
|
|
1495
|
+
if (agentType === "grok-build" && launchArgv.length === 0 && !resumeId && !hasMcpServers && prewarmedGrokHandle) {
|
|
1404
1496
|
if (prewarmedGrokCwd === normalizedPath) {
|
|
1405
1497
|
console.time(`ensure_session_${sessionId}`);
|
|
1406
1498
|
console.log(`[PRE-WARM] 🚀 Instant hit! Reusing pre-warmed grok-build handle for CWD=${normalizedPath}, session=${sessionId}`);
|
|
1499
|
+
// Take the spare before awaiting: concurrent ensure_session calls would otherwise adopt the same process.
|
|
1500
|
+
const spare = prewarmedGrokHandle;
|
|
1501
|
+
prewarmedGrokHandle = null;
|
|
1502
|
+
prewarmedGrokCwd = null;
|
|
1407
1503
|
const handle = await runtime.adoptSession({
|
|
1408
|
-
handle:
|
|
1504
|
+
handle: spare,
|
|
1409
1505
|
sessionKey: sessionId,
|
|
1410
1506
|
});
|
|
1411
|
-
prewarmedGrokHandle = null;
|
|
1412
|
-
prewarmedGrokCwd = null;
|
|
1413
1507
|
console.timeEnd(`ensure_session_${sessionId}`);
|
|
1414
|
-
//
|
|
1415
|
-
|
|
1508
|
+
// An earlier CAPACITY_PENDING attempt left this capacityId queued. The adopted process
|
|
1509
|
+
// already holds its own lease, so the entry would sit at the FIFO head and block every later launch.
|
|
1510
|
+
if (typeof payload.capacityId === "string" && payload.capacityId.trim()) {
|
|
1511
|
+
await processCapacity.cancel({ id: payload.capacityId.trim(), kind: "process" });
|
|
1512
|
+
}
|
|
1416
1513
|
activeSessions.set(sessionId, {
|
|
1417
1514
|
handle,
|
|
1418
1515
|
activeTurn: null,
|
|
@@ -1450,6 +1547,28 @@ export async function dispatchCommand(ws, payload) {
|
|
|
1450
1547
|
prewarmedGrokCwd = null;
|
|
1451
1548
|
}
|
|
1452
1549
|
}
|
|
1550
|
+
if (typeof payload.capacityId === "string" && payload.capacityId.trim()) {
|
|
1551
|
+
const capacityId = payload.capacityId.trim();
|
|
1552
|
+
if (capacityId.length > 4096) {
|
|
1553
|
+
sendError(ws, sessionId, "INVALID_PARAMS", "capacityId is invalid");
|
|
1554
|
+
console.timeEnd(`ensure_session_${sessionId}`);
|
|
1555
|
+
break;
|
|
1556
|
+
}
|
|
1557
|
+
const admission = await processCapacity.tryAdmit({ kind: "process", source: "automatic", id: capacityId, origin: capacityId.startsWith("a2a-") ? "job" : "user-opened" }, { signal: initializationSignal });
|
|
1558
|
+
if (admission?.pending === true) {
|
|
1559
|
+
sendCapacityPending(ws, sessionId, admission);
|
|
1560
|
+
console.timeEnd(`ensure_session_${sessionId}`);
|
|
1561
|
+
break;
|
|
1562
|
+
}
|
|
1563
|
+
const previousLease = preparedProcessLeases.get(runtimeSessionKey);
|
|
1564
|
+
if (previousLease && previousLease !== admission) {
|
|
1565
|
+
try {
|
|
1566
|
+
await previousLease.release();
|
|
1567
|
+
}
|
|
1568
|
+
catch { /* A later exit observation retries release. */ }
|
|
1569
|
+
}
|
|
1570
|
+
preparedProcessLeases.set(runtimeSessionKey, admission);
|
|
1571
|
+
}
|
|
1453
1572
|
console.log(`[acpx-server] Initializing session. Agent: ${agentType}, Cwd: ${normalizedPath}, ResumeSessionId: ${resumeId || "<none>"}`);
|
|
1454
1573
|
console.time(`ensure_session_${sessionId}`);
|
|
1455
1574
|
let profileResumeFallback = profileChanged && !resumeId;
|
|
@@ -1499,10 +1618,6 @@ export async function dispatchCommand(ws, payload) {
|
|
|
1499
1618
|
initialization.controller.signal.throwIfAborted();
|
|
1500
1619
|
console.timeEnd(`ensure_session_${sessionId}`);
|
|
1501
1620
|
console.log(`[DEBUG] ensure_session finished for session=${sessionId}`);
|
|
1502
|
-
// Asynchronously trigger background pre-warm after a cold spawn using the new CWD
|
|
1503
|
-
if (agentType === "grok-build" && launchArgv.length === 0) {
|
|
1504
|
-
setTimeout(() => prewarmGrokSession(normalizedPath), 500);
|
|
1505
|
-
}
|
|
1506
1621
|
activeSessions.set(sessionId, {
|
|
1507
1622
|
handle,
|
|
1508
1623
|
activeTurn: null,
|
|
@@ -1546,6 +1661,14 @@ export async function dispatchCommand(ws, payload) {
|
|
|
1546
1661
|
}
|
|
1547
1662
|
}
|
|
1548
1663
|
catch (error) {
|
|
1664
|
+
const leftover = preparedProcessLeases.get(runtimeSessionKey);
|
|
1665
|
+
if (leftover) {
|
|
1666
|
+
preparedProcessLeases.delete(runtimeSessionKey);
|
|
1667
|
+
try {
|
|
1668
|
+
await leftover.release();
|
|
1669
|
+
}
|
|
1670
|
+
catch { /* A later exit observation retries release. */ }
|
|
1671
|
+
}
|
|
1549
1672
|
if (initialization.controller.signal.aborted && initializedHandle) {
|
|
1550
1673
|
const current = activeSessions.get(sessionId);
|
|
1551
1674
|
if (current?.handle === initializedHandle) {
|
|
@@ -2020,12 +2143,14 @@ export async function dispatchCommand(ws, payload) {
|
|
|
2020
2143
|
if (session) {
|
|
2021
2144
|
console.log(`[acpx-server] Closing session: ${sessionId}`);
|
|
2022
2145
|
unregisterAgentSessionMapping(session.handle);
|
|
2146
|
+
const pid = (await loadActiveSessionRecord(runtime, session.handle))?.pid;
|
|
2023
2147
|
try {
|
|
2024
2148
|
if (session.activeTurn) {
|
|
2025
2149
|
await session.activeTurn.cancel({ reason: "Session closed" });
|
|
2026
2150
|
}
|
|
2027
2151
|
await cancelSessionQueue(session, sessionId);
|
|
2028
2152
|
await runtime.close({ handle: session.handle, reason: "Session closed by request" });
|
|
2153
|
+
sessionMcpServers.delete(session.handle.sessionKey);
|
|
2029
2154
|
}
|
|
2030
2155
|
catch (err) {
|
|
2031
2156
|
console.error(`[acpx-server] Error closing runtime handle:`, err);
|
|
@@ -2033,6 +2158,7 @@ export async function dispatchCommand(ws, payload) {
|
|
|
2033
2158
|
}
|
|
2034
2159
|
activeSessions.delete(sessionId);
|
|
2035
2160
|
sessionBackgroundTasks.delete(sessionId);
|
|
2161
|
+
ws.send(JSON.stringify({ event: "session_released", sessionId, processReleased: await confirmProcessReleased(pid) }));
|
|
2036
2162
|
}
|
|
2037
2163
|
clearSessionHistoryPush(sessionId);
|
|
2038
2164
|
break;
|
|
@@ -2272,6 +2398,15 @@ export async function dispatchCommand(ws, payload) {
|
|
|
2272
2398
|
ws.send(JSON.stringify({ event: "all_sessions_closed" }));
|
|
2273
2399
|
break;
|
|
2274
2400
|
}
|
|
2401
|
+
case "capacity_cancel": {
|
|
2402
|
+
const capacityId = typeof payload.capacityId === "string" ? payload.capacityId.trim() : "";
|
|
2403
|
+
if (!capacityId || capacityId.length > 4096) {
|
|
2404
|
+
sendError(ws, sessionId, "INVALID_PARAMS", "capacityId is required");
|
|
2405
|
+
return;
|
|
2406
|
+
}
|
|
2407
|
+
await processCapacity.cancel({ id: capacityId, kind: "process" });
|
|
2408
|
+
break;
|
|
2409
|
+
}
|
|
2275
2410
|
default:
|
|
2276
2411
|
sendError(ws, sessionId, "UNKNOWN_ACTION", `Action ${action} is not supported`);
|
|
2277
2412
|
}
|
|
@@ -2414,6 +2549,17 @@ function notifySessionTakenOver(previousWs, nextWs, sessionId) {
|
|
|
2414
2549
|
console.warn(`[acpx-server] Failed to notify taken-over ws for ${sessionId}:`, err.message);
|
|
2415
2550
|
}
|
|
2416
2551
|
}
|
|
2552
|
+
function sendCapacityPending(ws, sessionId, pending) {
|
|
2553
|
+
ws.send(JSON.stringify({
|
|
2554
|
+
event: "error",
|
|
2555
|
+
sessionId,
|
|
2556
|
+
code: "CAPACITY_PENDING",
|
|
2557
|
+
message: "CAPACITY_PENDING",
|
|
2558
|
+
scope: "control",
|
|
2559
|
+
terminal: false,
|
|
2560
|
+
data: { position: pending.position, waitedMs: pending.waitedMs },
|
|
2561
|
+
}));
|
|
2562
|
+
}
|
|
2417
2563
|
// Helper for sending error events
|
|
2418
2564
|
function sendError(ws, sessionId, errorCode, message) {
|
|
2419
2565
|
ws.send(JSON.stringify({
|
|
@@ -2932,13 +3078,13 @@ async function handleExitPlanModeCallback(req, ctx) {
|
|
|
2932
3078
|
event: "exit_plan_mode_timeout",
|
|
2933
3079
|
requestId,
|
|
2934
3080
|
toolCallId,
|
|
2935
|
-
message:
|
|
3081
|
+
message: `exit_plan_mode auto-abandoned after ${interactionTimeoutText()} timeout.`,
|
|
2936
3082
|
});
|
|
2937
3083
|
}
|
|
2938
3084
|
catch {
|
|
2939
3085
|
// socket may already be closed
|
|
2940
3086
|
}
|
|
2941
|
-
},
|
|
3087
|
+
}, interactionTimeoutMs());
|
|
2942
3088
|
const payload = {
|
|
2943
3089
|
event: "exit_plan_mode",
|
|
2944
3090
|
sessionId: clientSessionId,
|
|
@@ -3001,13 +3147,13 @@ async function handleAskUserQuestionCallback(req, ctx) {
|
|
|
3001
3147
|
event: "ask_user_question_timeout",
|
|
3002
3148
|
requestId,
|
|
3003
3149
|
toolCallId,
|
|
3004
|
-
message:
|
|
3150
|
+
message: `ask_user_question auto-cancelled after ${interactionTimeoutText()} timeout.`,
|
|
3005
3151
|
});
|
|
3006
3152
|
}
|
|
3007
3153
|
catch {
|
|
3008
3154
|
// socket may already be closed
|
|
3009
3155
|
}
|
|
3010
|
-
},
|
|
3156
|
+
}, interactionTimeoutMs());
|
|
3011
3157
|
const payload = {
|
|
3012
3158
|
event: "ask_user_question",
|
|
3013
3159
|
sessionId: clientSessionId,
|
|
@@ -3087,19 +3233,25 @@ async function handlePermissionRequestCallback(req, ctx) {
|
|
|
3087
3233
|
(req.inferredKind === "edit" || req.inferredKind === "move" || req.inferredKind === "delete")) {
|
|
3088
3234
|
return { outcome: "allow_once" };
|
|
3089
3235
|
}
|
|
3090
|
-
//
|
|
3091
|
-
//
|
|
3092
|
-
//
|
|
3093
|
-
//
|
|
3094
|
-
//
|
|
3236
|
+
// Bridge permissionMode (approve-reads / approve-all / deny-all) is not
|
|
3237
|
+
// applied. Tool posture follows ACP settings the user can select or import:
|
|
3238
|
+
// native mode (session/set_mode; Grok handled above) and config options such
|
|
3239
|
+
// as reasoning effort (session/set_config_option). Other agents fall through
|
|
3240
|
+
// to project allow-rules and a prompt.
|
|
3241
|
+
/*
|
|
3095
3242
|
if (!grokMode && session.permissionMode === "approve-all") {
|
|
3096
|
-
|
|
3097
|
-
|
|
3243
|
+
console.log(
|
|
3244
|
+
`[acpx-server] permission mode=approve-all → auto allow_once for ${req.raw.toolCall.title}`,
|
|
3245
|
+
);
|
|
3246
|
+
return { outcome: "allow_once" };
|
|
3098
3247
|
}
|
|
3099
3248
|
if (!grokMode && session.permissionMode === "deny-all") {
|
|
3100
|
-
|
|
3101
|
-
|
|
3249
|
+
console.log(
|
|
3250
|
+
`[acpx-server] permission mode=deny-all → auto reject_once for ${req.raw.toolCall.title}`,
|
|
3251
|
+
);
|
|
3252
|
+
return { outcome: "reject_once" };
|
|
3102
3253
|
}
|
|
3254
|
+
*/
|
|
3103
3255
|
// Project-level "总是允许" allowlist: a prior allow_always for this
|
|
3104
3256
|
// tool+prefix auto-approves without prompting again. Read fresh from the
|
|
3105
3257
|
// project file so it survives reap/resume/restart and is shared across
|
|
@@ -3113,7 +3265,7 @@ async function handlePermissionRequestCallback(req, ctx) {
|
|
|
3113
3265
|
const requestId = `perm_${nextRequestId++}`;
|
|
3114
3266
|
console.log(`[acpx-server] Intercepted permission request: ${req.raw.toolCall.title}. RequestId: ${requestId} for client session: ${clientSessionId}`);
|
|
3115
3267
|
return new Promise((resolve, reject) => {
|
|
3116
|
-
// Timeout handler:
|
|
3268
|
+
// Timeout handler: auto-deny after the interaction timeout
|
|
3117
3269
|
const timer = setTimeout(() => {
|
|
3118
3270
|
console.warn(`[acpx-server] Permission request ${requestId} timed out. Auto-denying.`);
|
|
3119
3271
|
pendingPermissions.delete(requestId);
|
|
@@ -3122,9 +3274,9 @@ async function handlePermissionRequestCallback(req, ctx) {
|
|
|
3122
3274
|
sendRuntimeTurnEvent(session.ws, clientSessionId, session.activeTurn, {
|
|
3123
3275
|
event: "permission_timeout",
|
|
3124
3276
|
requestId,
|
|
3125
|
-
message: `Permission request for "${req.raw.toolCall.title}" auto-denied after
|
|
3277
|
+
message: `Permission request for "${req.raw.toolCall.title}" auto-denied after ${interactionTimeoutText()} timeout.`,
|
|
3126
3278
|
});
|
|
3127
|
-
},
|
|
3279
|
+
}, interactionTimeoutMs());
|
|
3128
3280
|
// Save pending info — include session and full payload so the reconnect
|
|
3129
3281
|
// path can re-deliver the event to a new WebSocket without re-running
|
|
3130
3282
|
// the permission logic.
|
|
@@ -3251,6 +3403,6 @@ export function attachProcessSignalHandlers() {
|
|
|
3251
3403
|
void gracefulExit("SIGTERM");
|
|
3252
3404
|
});
|
|
3253
3405
|
}
|
|
3254
|
-
export { runtime, activeSessions, sessionBackgroundTasks, killAllManagedAgents, gracefulExit, };
|
|
3406
|
+
export { runtime, activeSessions, sessionBackgroundTasks, killAllManagedAgents, gracefulExit, prewarmGrokSession, };
|
|
3255
3407
|
export { pendingPermissions, pendingAskUserQuestions, pendingExitPlanModes, loadSessionHistory };
|
|
3256
3408
|
export async function readRuntimeRecord(id) { return runtime.options.sessionStore.load(id); }
|
|
@@ -4,6 +4,12 @@ export interface CapacityQueueWaitOptions {
|
|
|
4
4
|
/** Called once only when admission actually has to wait. */
|
|
5
5
|
onPending?: () => void;
|
|
6
6
|
}
|
|
7
|
+
/** Non-blocking FIFO result. The queue entry stays until admission or cancel. */
|
|
8
|
+
export interface CapacityPendingAdmission {
|
|
9
|
+
pending: true;
|
|
10
|
+
position: number;
|
|
11
|
+
waitedMs: number;
|
|
12
|
+
}
|
|
7
13
|
export interface CapacityQueueTimingOptions {
|
|
8
14
|
pollIntervalMs?: number;
|
|
9
15
|
}
|
|
@@ -13,6 +19,35 @@ export declare class CapacityQueue {
|
|
|
13
19
|
private readonly pollIntervalMs;
|
|
14
20
|
constructor(options?: CapacityOptions, timing?: CapacityQueueTimingOptions);
|
|
15
21
|
acquire(request: CapacityRequest, { signal, onPending }?: CapacityQueueWaitOptions): Promise<CapacityLease>;
|
|
22
|
+
/**
|
|
23
|
+
* Enqueue if needed and return immediately.
|
|
24
|
+
* A free head slot is acquired in this same call. A full slot keeps the entry and reports position.
|
|
25
|
+
* Retries with the same id reuse that entry. Callers without a queue id keep using acquire().
|
|
26
|
+
*/
|
|
27
|
+
tryAdmit(request: CapacityRequest, { signal }?: {
|
|
28
|
+
signal?: AbortSignal;
|
|
29
|
+
}): Promise<CapacityLease | CapacityPendingAdmission>;
|
|
30
|
+
/** Age of the oldest still-owned queue entry. Missing queues and dead owners are not rewritten. */
|
|
31
|
+
headWaitMs(kind: CapacityRequest['kind']): Promise<number>;
|
|
32
|
+
/** Current admission counts. Uses this queue's governor, including its configured limit. */
|
|
33
|
+
slotView(): Promise<{
|
|
34
|
+
taskSlot: {
|
|
35
|
+
limit: number;
|
|
36
|
+
used: number;
|
|
37
|
+
};
|
|
38
|
+
processSlot: {
|
|
39
|
+
limit: number;
|
|
40
|
+
used: number;
|
|
41
|
+
headWaitMs: number;
|
|
42
|
+
};
|
|
43
|
+
}>;
|
|
44
|
+
/** True while a process lease still names this child pid. */
|
|
45
|
+
holdsChild(pid: number): Promise<boolean>;
|
|
46
|
+
/** Drop this process's queued entry. A lease already returned to the caller is not released here. */
|
|
47
|
+
cancel(request: {
|
|
48
|
+
id: string;
|
|
49
|
+
kind: CapacityRequest['kind'];
|
|
50
|
+
}): Promise<boolean>;
|
|
16
51
|
private entryPath;
|
|
17
52
|
private readState;
|
|
18
53
|
private readJson;
|
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
/** Durable device-wide FIFO admission for automatically invoked ACP work. */
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
|
-
import { closeSync, constants, fstatSync, fsyncSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { closeSync, constants, existsSync, fstatSync, fsyncSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
6
|
import { DirectoryLease } from './a2a/lease.js';
|
|
7
7
|
import { CapacityError, CapacityGovernor, resolveCapacityDirectory } from './capacity.js';
|
|
8
8
|
const tokenPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
|
|
9
9
|
const stateMessage = 'ACP capacity queue state is unavailable; check the local host queue state before retrying.';
|
|
10
|
+
const processOrigins = new Set(['prewarm', 'job', 'user-opened']);
|
|
10
11
|
const validRequest = (value) => !!value &&
|
|
11
12
|
(value.kind === 'task' || value.kind === 'process') &&
|
|
12
13
|
(value.source === 'automatic' || value.source === 'interactive') &&
|
|
13
|
-
typeof value.id === 'string' && !!value.id.trim() && value.id.length <= 4096
|
|
14
|
+
typeof value.id === 'string' && !!value.id.trim() && value.id.length <= 4096 &&
|
|
15
|
+
(value.origin === undefined || (value.kind === 'process' && processOrigins.has(value.origin)));
|
|
14
16
|
const isPositiveInteger = (value) => Number.isSafeInteger(value) && value > 0;
|
|
15
17
|
/** Permission failures do not prove that a queued owner has exited. */
|
|
16
18
|
function isDead(pid) {
|
|
@@ -118,6 +120,141 @@ export class CapacityQueue {
|
|
|
118
120
|
}
|
|
119
121
|
}
|
|
120
122
|
}
|
|
123
|
+
/**
|
|
124
|
+
* Enqueue if needed and return immediately.
|
|
125
|
+
* A free head slot is acquired in this same call. A full slot keeps the entry and reports position.
|
|
126
|
+
* Retries with the same id reuse that entry. Callers without a queue id keep using acquire().
|
|
127
|
+
*/
|
|
128
|
+
async tryAdmit(request, { signal } = {}) {
|
|
129
|
+
if (!validRequest(request))
|
|
130
|
+
throw new Error('Invalid ACP capacity request');
|
|
131
|
+
signal?.throwIfAborted();
|
|
132
|
+
if (request.source === 'interactive') {
|
|
133
|
+
const lease = await this.governor.acquire(request);
|
|
134
|
+
if (signal?.aborted) {
|
|
135
|
+
await lease.release();
|
|
136
|
+
signal.throwIfAborted();
|
|
137
|
+
}
|
|
138
|
+
return lease;
|
|
139
|
+
}
|
|
140
|
+
let acquired;
|
|
141
|
+
let pending;
|
|
142
|
+
let created = false;
|
|
143
|
+
let entry;
|
|
144
|
+
try {
|
|
145
|
+
await this.transaction(async () => {
|
|
146
|
+
signal?.throwIfAborted();
|
|
147
|
+
const state = this.readState();
|
|
148
|
+
const existing = state.entries.find(item => item.id === request.id && item.kind === request.kind && item.ownerPid === process.pid);
|
|
149
|
+
if (existing)
|
|
150
|
+
entry = existing;
|
|
151
|
+
else {
|
|
152
|
+
if (state.lastSequence >= Number.MAX_SAFE_INTEGER)
|
|
153
|
+
throw new Error(stateMessage);
|
|
154
|
+
entry = { ...request, version: 1, token: randomUUID(), ownerPid: process.pid,
|
|
155
|
+
enqueuedAt: Date.now(), sequence: state.lastSequence + 1 };
|
|
156
|
+
this.writeJson(join(this.directory, 'counter.json'), { version: 1, lastSequence: entry.sequence });
|
|
157
|
+
created = true;
|
|
158
|
+
this.writeJson(this.entryPath(entry.token), entry);
|
|
159
|
+
}
|
|
160
|
+
const current = this.readState();
|
|
161
|
+
const own = current.entries.find(item => item.token === entry.token);
|
|
162
|
+
if (!own || own.ownerPid !== process.pid)
|
|
163
|
+
throw new Error(stateMessage);
|
|
164
|
+
const same = current.entries.filter(item => item.kind === request.kind);
|
|
165
|
+
const position = same.findIndex(item => item.token === own.token) + 1;
|
|
166
|
+
const waitedMs = Math.max(0, Date.now() - own.enqueuedAt);
|
|
167
|
+
if (position < 1)
|
|
168
|
+
throw new Error(stateMessage);
|
|
169
|
+
const head = same[0];
|
|
170
|
+
if (head?.token !== own.token) {
|
|
171
|
+
pending = { pending: true, position, waitedMs };
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
try {
|
|
175
|
+
acquired = await this.governor.acquire(request);
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
if (error instanceof CapacityError) {
|
|
179
|
+
pending = { pending: true, position, waitedMs };
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
throw error;
|
|
183
|
+
}
|
|
184
|
+
this.removeEntry(own);
|
|
185
|
+
created = false;
|
|
186
|
+
}, signal);
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
if (created && entry)
|
|
190
|
+
await this.transaction(() => this.removeEntry(entry)).catch(() => undefined);
|
|
191
|
+
throw error;
|
|
192
|
+
}
|
|
193
|
+
if (signal?.aborted) {
|
|
194
|
+
if (acquired)
|
|
195
|
+
await acquired.release();
|
|
196
|
+
else if (entry)
|
|
197
|
+
await this.transaction(() => this.removeEntry(entry)).catch(() => undefined);
|
|
198
|
+
signal.throwIfAborted();
|
|
199
|
+
}
|
|
200
|
+
if (acquired)
|
|
201
|
+
return acquired;
|
|
202
|
+
if (!pending)
|
|
203
|
+
throw new Error(stateMessage);
|
|
204
|
+
return pending;
|
|
205
|
+
}
|
|
206
|
+
/** Age of the oldest still-owned queue entry. Missing queues and dead owners are not rewritten. */
|
|
207
|
+
async headWaitMs(kind) {
|
|
208
|
+
if (kind !== 'task' && kind !== 'process')
|
|
209
|
+
throw new Error('Invalid ACP capacity request');
|
|
210
|
+
if (!existsSync(this.directory))
|
|
211
|
+
return 0;
|
|
212
|
+
return this.transaction(() => {
|
|
213
|
+
let head;
|
|
214
|
+
for (const name of readdirSync(this.directory)) {
|
|
215
|
+
if (name === '.lock' || name === 'counter.json' || /^pending-[a-f0-9-]{36}\.json$/.test(name))
|
|
216
|
+
continue;
|
|
217
|
+
if (!/^entry-[a-f0-9-]{36}\.json$/.test(name))
|
|
218
|
+
throw new Error(stateMessage);
|
|
219
|
+
const entry = this.readEntry(join(this.directory, name));
|
|
220
|
+
if (name !== `entry-${entry.token}.json` || entry.kind !== kind || isDead(entry.ownerPid))
|
|
221
|
+
continue;
|
|
222
|
+
if (!head || entry.sequence < head.sequence)
|
|
223
|
+
head = entry;
|
|
224
|
+
}
|
|
225
|
+
return head ? Math.max(0, Date.now() - head.enqueuedAt) : 0;
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
/** Current admission counts. Uses this queue's governor, including its configured limit. */
|
|
229
|
+
async slotView() {
|
|
230
|
+
const task = await this.governor.snapshot('task');
|
|
231
|
+
const process = await this.governor.snapshot('process');
|
|
232
|
+
return {
|
|
233
|
+
taskSlot: { limit: task.limits.soft, used: task.used },
|
|
234
|
+
processSlot: { limit: process.limits.soft, used: process.used, headWaitMs: await this.headWaitMs('process') },
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
/** True while a process lease still names this child pid. */
|
|
238
|
+
async holdsChild(pid) {
|
|
239
|
+
const { sessions } = await this.governor.inspect();
|
|
240
|
+
return Object.values(sessions).some(rows => rows.some(row => row.childPid === pid));
|
|
241
|
+
}
|
|
242
|
+
/** Drop this process's queued entry. A lease already returned to the caller is not released here. */
|
|
243
|
+
async cancel(request) {
|
|
244
|
+
if (typeof request.id !== 'string' || !request.id.trim() || request.id.length > 4096)
|
|
245
|
+
throw new Error('Invalid ACP capacity request');
|
|
246
|
+
if (request.kind !== 'task' && request.kind !== 'process')
|
|
247
|
+
throw new Error('Invalid ACP capacity request');
|
|
248
|
+
let removed = false;
|
|
249
|
+
await this.transaction(() => {
|
|
250
|
+
const own = this.readState().entries.find(item => item.id === request.id && item.kind === request.kind && item.ownerPid === process.pid);
|
|
251
|
+
if (!own)
|
|
252
|
+
return;
|
|
253
|
+
this.removeEntry(own);
|
|
254
|
+
removed = true;
|
|
255
|
+
});
|
|
256
|
+
return removed;
|
|
257
|
+
}
|
|
121
258
|
entryPath(token) { return join(this.directory, `entry-${token}.json`); }
|
|
122
259
|
readState() {
|
|
123
260
|
const entries = [];
|