dsh-agy-link 0.6.59 → 0.6.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/dist/cli-image.mjs +103 -16
- package/dist/client.js +16 -0
- package/dist/index.js +1007 -32
- package/docs/CONFIGURATION.md +3 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -11,7 +11,7 @@ import { EventEmitter } from "node:events";
|
|
|
11
11
|
import { promisify } from "node:util";
|
|
12
12
|
import { copyFile, mkdir, mkdtemp, open, readFile, readdir, realpath, rm, stat, unlink, writeFile } from "node:fs/promises";
|
|
13
13
|
import * as dshLlm from "@deepseek-ai/dsh-llm";
|
|
14
|
-
import { LlmAdapter, LlmError, createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
14
|
+
import { LlmAdapter, LlmError, boundContextSummary, createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
15
15
|
import { StringDecoder } from "node:string_decoder";
|
|
16
16
|
//#region \0rolldown/runtime.js
|
|
17
17
|
var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
|
|
@@ -189,7 +189,10 @@ function defaultConfig() {
|
|
|
189
189
|
imageTimeoutMs: 24e4,
|
|
190
190
|
imageMaxBytes: 20971520,
|
|
191
191
|
imageOutputDir: "",
|
|
192
|
-
imageRetries: 1
|
|
192
|
+
imageRetries: 1,
|
|
193
|
+
backgroundWakeup: false,
|
|
194
|
+
backgroundWakeupTtlMinutes: 30,
|
|
195
|
+
backgroundWakeupMaxPerSession: 12
|
|
193
196
|
};
|
|
194
197
|
}
|
|
195
198
|
//#endregion
|
|
@@ -2575,7 +2578,10 @@ function resolveConfig(entry, env = process.env, overrides = readOverrides()) {
|
|
|
2575
2578
|
imageTimeoutMs: asNum(get("imageTimeoutMs")) ?? base.imageTimeoutMs,
|
|
2576
2579
|
imageMaxBytes: asNum(get("imageMaxBytes")) ?? base.imageMaxBytes,
|
|
2577
2580
|
imageOutputDir: asString(get("imageOutputDir")) ?? base.imageOutputDir,
|
|
2578
|
-
imageRetries: asNum(get("imageRetries")) ?? base.imageRetries
|
|
2581
|
+
imageRetries: asNum(get("imageRetries")) ?? base.imageRetries,
|
|
2582
|
+
backgroundWakeup: asBool(get("backgroundWakeup")) ?? base.backgroundWakeup,
|
|
2583
|
+
backgroundWakeupTtlMinutes: asNum(get("backgroundWakeupTtlMinutes")) ?? base.backgroundWakeupTtlMinutes,
|
|
2584
|
+
backgroundWakeupMaxPerSession: asNum(get("backgroundWakeupMaxPerSession")) ?? base.backgroundWakeupMaxPerSession
|
|
2579
2585
|
};
|
|
2580
2586
|
if (env.DSH_AGY_ENABLED !== void 0) cfg.enabled = asBool(env.DSH_AGY_ENABLED) ?? cfg.enabled;
|
|
2581
2587
|
if (env.DSH_AGY_BIN) cfg.agyBin = env.DSH_AGY_BIN;
|
|
@@ -2731,6 +2737,20 @@ function resolveConfig(entry, env = process.env, overrides = readOverrides()) {
|
|
|
2731
2737
|
const v = asNum(env.DSH_AGY_IMAGE_RETRIES);
|
|
2732
2738
|
if (v !== void 0) cfg.imageRetries = v;
|
|
2733
2739
|
}
|
|
2740
|
+
if (env.DSH_AGY_BACKGROUND_WAKEUP !== void 0) {
|
|
2741
|
+
const bw = asBool(env.DSH_AGY_BACKGROUND_WAKEUP);
|
|
2742
|
+
if (bw !== void 0) cfg.backgroundWakeup = bw;
|
|
2743
|
+
}
|
|
2744
|
+
if (env.DSH_AGY_BACKGROUND_WAKEUP_TTL_MINUTES) {
|
|
2745
|
+
const ttl = asNum(env.DSH_AGY_BACKGROUND_WAKEUP_TTL_MINUTES);
|
|
2746
|
+
if (ttl !== void 0 && ttl > 0) cfg.backgroundWakeupTtlMinutes = Math.min(240, Math.max(1, Math.floor(ttl)));
|
|
2747
|
+
}
|
|
2748
|
+
if (env.DSH_AGY_BACKGROUND_WAKEUP_MAX_PER_SESSION) {
|
|
2749
|
+
const max = asNum(env.DSH_AGY_BACKGROUND_WAKEUP_MAX_PER_SESSION);
|
|
2750
|
+
if (max !== void 0 && max > 0) cfg.backgroundWakeupMaxPerSession = Math.min(100, Math.max(1, Math.floor(max)));
|
|
2751
|
+
}
|
|
2752
|
+
cfg.backgroundWakeupTtlMinutes = Math.min(240, Math.max(1, Math.floor(cfg.backgroundWakeupTtlMinutes)));
|
|
2753
|
+
cfg.backgroundWakeupMaxPerSession = Math.min(100, Math.max(1, Math.floor(cfg.backgroundWakeupMaxPerSession)));
|
|
2734
2754
|
return cfg;
|
|
2735
2755
|
}
|
|
2736
2756
|
//#endregion
|
|
@@ -30658,6 +30678,15 @@ const waiters = Symbol("waiters");
|
|
|
30658
30678
|
function isConsumableResult(ev) {
|
|
30659
30679
|
return (ev.ok || ev.response !== "") && !isNonConsumableResultError(ev.ok, ev.error, ev.response);
|
|
30660
30680
|
}
|
|
30681
|
+
/**
|
|
30682
|
+
* True when a usage sample carries a token breakdown rather than a bare input
|
|
30683
|
+
* count. Only such samples may stand in for the result envelope's usage; see
|
|
30684
|
+
* `finalUsage` and issue #158.
|
|
30685
|
+
*/
|
|
30686
|
+
function hasUsageBreakdown(raw) {
|
|
30687
|
+
const positive = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
|
|
30688
|
+
return positive(raw.output_tokens) || positive(raw.cache_read_tokens) || positive(raw.cache_write_tokens) || positive(raw.thinking_tokens) || positive(raw.total_tokens);
|
|
30689
|
+
}
|
|
30661
30690
|
/** One agy run's append-only event log plus its settlement state. */
|
|
30662
30691
|
var RunRecording = class {
|
|
30663
30692
|
now;
|
|
@@ -30759,6 +30788,17 @@ var RunRecording = class {
|
|
|
30759
30788
|
if (s.outputTokens > 0 && s.lastAt - s.startedAt >= 500) lastTps = s.outputTokens / ((s.lastAt - s.startedAt) / 1e3);
|
|
30760
30789
|
break;
|
|
30761
30790
|
}
|
|
30791
|
+
if (tokens === 0) {
|
|
30792
|
+
const envelope = this.envelopeOutputTokens();
|
|
30793
|
+
const spanMs = this.eventSpanMs();
|
|
30794
|
+
if (envelope > 0 && spanMs >= 500) return {
|
|
30795
|
+
lastTps: envelope / (spanMs / 1e3),
|
|
30796
|
+
avgTps: envelope / (spanMs / 1e3),
|
|
30797
|
+
outputTokens: envelope,
|
|
30798
|
+
measuredSteps: 1,
|
|
30799
|
+
generatingMs: spanMs
|
|
30800
|
+
};
|
|
30801
|
+
}
|
|
30762
30802
|
return {
|
|
30763
30803
|
lastTps,
|
|
30764
30804
|
avgTps: ms > 0 ? tokens / (ms / 1e3) : null,
|
|
@@ -30767,6 +30807,23 @@ var RunRecording = class {
|
|
|
30767
30807
|
generatingMs: ms
|
|
30768
30808
|
};
|
|
30769
30809
|
}
|
|
30810
|
+
/** Output tokens reported by the last result envelope (0 when it has none). */
|
|
30811
|
+
envelopeOutputTokens() {
|
|
30812
|
+
for (let i = this.events.length - 1; i >= 0; i--) {
|
|
30813
|
+
const ev = this.events[i];
|
|
30814
|
+
if (ev === void 0 || ev.kind !== "result" || ev.usage === void 0) continue;
|
|
30815
|
+
const out = ev.usage.output_tokens;
|
|
30816
|
+
return typeof out === "number" && Number.isFinite(out) && out > 0 ? out : 0;
|
|
30817
|
+
}
|
|
30818
|
+
return 0;
|
|
30819
|
+
}
|
|
30820
|
+
/** Wall-clock span between the first and the last recorded event. */
|
|
30821
|
+
eventSpanMs() {
|
|
30822
|
+
const first = this.eventTimes[0];
|
|
30823
|
+
const last = this.eventTimes[this.eventTimes.length - 1];
|
|
30824
|
+
if (first === void 0 || last === void 0) return 0;
|
|
30825
|
+
return last - first;
|
|
30826
|
+
}
|
|
30770
30827
|
/**
|
|
30771
30828
|
* Usage accounting (verified against agy 1.1.16 stream-json): step_update
|
|
30772
30829
|
* usage is PER-CALL (the current context size at that internal LLM call),
|
|
@@ -30783,9 +30840,22 @@ var RunRecording = class {
|
|
|
30783
30840
|
get lastUsage() {
|
|
30784
30841
|
return this.lastStepUsageRaw;
|
|
30785
30842
|
}
|
|
30786
|
-
/**
|
|
30843
|
+
/**
|
|
30844
|
+
* The usage to report for the result envelope: the last per-call step sample
|
|
30845
|
+
* when it actually carries a token breakdown, otherwise the envelope's own
|
|
30846
|
+
* usage.
|
|
30847
|
+
*
|
|
30848
|
+
* The sample is only preferred when it reports output / cache / thinking
|
|
30849
|
+
* tokens. A sample that carries nothing but an input figure is a context
|
|
30850
|
+
* occupancy reading, not a usage sample: agy's ACP `usage_update` sends
|
|
30851
|
+
* `{ used, size }`, and promoting that to `{inputTokens: used,
|
|
30852
|
+
* outputTokens: 0}` used to shadow the real `PromptResponse.usage` (0%
|
|
30853
|
+
* cache hit, 0 tok/s, inflated uncached input — issue #158).
|
|
30854
|
+
*/
|
|
30787
30855
|
finalUsage(resultRaw) {
|
|
30788
|
-
|
|
30856
|
+
const step = this.lastStepUsageRaw;
|
|
30857
|
+
if (step === null) return resultRaw;
|
|
30858
|
+
return hasUsageBreakdown(step) ? step : resultRaw;
|
|
30789
30859
|
}
|
|
30790
30860
|
/** Settle the recording: no further events will arrive. */
|
|
30791
30861
|
settle(failure) {
|
|
@@ -30862,6 +30932,10 @@ var RunRecording = class {
|
|
|
30862
30932
|
eventAt(index) {
|
|
30863
30933
|
return this.events[index];
|
|
30864
30934
|
}
|
|
30935
|
+
/** Arrival timestamp (ms) of the event at `index`, when recorded. */
|
|
30936
|
+
eventTimestampAt(index) {
|
|
30937
|
+
return this.eventTimes[index];
|
|
30938
|
+
}
|
|
30865
30939
|
/** Number of recorded events so far. */
|
|
30866
30940
|
get length() {
|
|
30867
30941
|
return this.events.length;
|
|
@@ -32767,13 +32841,10 @@ function buildToolCallBlock(input) {
|
|
|
32767
32841
|
arguments: argumentsJson
|
|
32768
32842
|
}
|
|
32769
32843
|
},
|
|
32770
|
-
{
|
|
32844
|
+
...trackedCut !== void 0 && Object.keys(trackedCut).length > 0 ? [{
|
|
32771
32845
|
type: "usage",
|
|
32772
|
-
usage:
|
|
32773
|
-
|
|
32774
|
-
outputTokens: 0
|
|
32775
|
-
}
|
|
32776
|
-
},
|
|
32846
|
+
usage: usageFromRaw(trackedCut)
|
|
32847
|
+
}] : [],
|
|
32777
32848
|
{
|
|
32778
32849
|
type: "finish",
|
|
32779
32850
|
reason: { kind: "tool-calls" }
|
|
@@ -33144,12 +33215,9 @@ var EventMapper = class {
|
|
|
33144
33215
|
const close = this.closeOpen();
|
|
33145
33216
|
if (close) yield close;
|
|
33146
33217
|
const tracked = this.opts.usage?.finalUsage({});
|
|
33147
|
-
yield {
|
|
33218
|
+
if (tracked !== void 0 && Object.keys(tracked).length > 0) yield {
|
|
33148
33219
|
type: "usage",
|
|
33149
|
-
usage:
|
|
33150
|
-
inputTokens: 0,
|
|
33151
|
-
outputTokens: 0
|
|
33152
|
-
}
|
|
33220
|
+
usage: usageFromRaw(tracked)
|
|
33153
33221
|
};
|
|
33154
33222
|
const failure = {
|
|
33155
33223
|
message,
|
|
@@ -37352,6 +37420,15 @@ async function handleAttemptOutcome(deps, input, ctx) {
|
|
|
37352
37420
|
} finally {
|
|
37353
37421
|
rec.settle(failure);
|
|
37354
37422
|
}
|
|
37423
|
+
if (!input.isAux && sessionKey !== "") deps.backgroundObserver?.onAttemptSettled?.({
|
|
37424
|
+
sessionKey,
|
|
37425
|
+
conversationId,
|
|
37426
|
+
...rec.accountHome === void 0 ? {} : { accountHome: rec.accountHome },
|
|
37427
|
+
transport: "cli",
|
|
37428
|
+
recording: rec,
|
|
37429
|
+
failure,
|
|
37430
|
+
superseded
|
|
37431
|
+
});
|
|
37355
37432
|
}
|
|
37356
37433
|
/**
|
|
37357
37434
|
* Run one attempt: recorder → slot dispatch → spawn → concurrent outcome.
|
|
@@ -37425,6 +37502,10 @@ var AgyAdapter = class extends LlmAdapter {
|
|
|
37425
37502
|
effortUnsupportedModels() {
|
|
37426
37503
|
return this.effortPolicy.unsupportedModels();
|
|
37427
37504
|
}
|
|
37505
|
+
/** Live in-flight recording for `sessionKey`, if any. */
|
|
37506
|
+
getActiveRun(sessionKey) {
|
|
37507
|
+
return this.activeRuns.get(sessionKey);
|
|
37508
|
+
}
|
|
37428
37509
|
/** True when `--effort` must not be passed to this model. */
|
|
37429
37510
|
isEffortUnsupported(model) {
|
|
37430
37511
|
return this.effortPolicy.isUnsupported(model);
|
|
@@ -37719,6 +37800,11 @@ var AgyAdapter = class extends LlmAdapter {
|
|
|
37719
37800
|
inFlight: true
|
|
37720
37801
|
});
|
|
37721
37802
|
}
|
|
37803
|
+
if (!isAux && sessionKey !== "") {
|
|
37804
|
+
const lastUser = [...messages].reverse().find((m) => m.role === "user");
|
|
37805
|
+
if (!(lastUser?.source?.kind === "plugin" && lastUser?.source?.plugin === "agy-link" && lastUser?.source?.form === "notice")) this.deps.backgroundObserver?.onHumanTurn?.(sessionKey);
|
|
37806
|
+
this.deps.backgroundObserver?.onAttemptStart?.(sessionKey);
|
|
37807
|
+
}
|
|
37722
37808
|
const rec = yield* runAgyAttempt({
|
|
37723
37809
|
acquire: (signal) => this.deps.acquire(signal),
|
|
37724
37810
|
pool: this.deps.pool,
|
|
@@ -37741,7 +37827,8 @@ var AgyAdapter = class extends LlmAdapter {
|
|
|
37741
37827
|
lastAccountSpawnTime: this.lastAccountSpawnTime,
|
|
37742
37828
|
minSpawnIntervalMs: this.minSpawnIntervalMs,
|
|
37743
37829
|
spawnLimiter: this.spawnLimiter,
|
|
37744
|
-
...this.deps.runAcp === void 0 ? {} : { runAcp: this.deps.runAcp }
|
|
37830
|
+
...this.deps.runAcp === void 0 ? {} : { runAcp: this.deps.runAcp },
|
|
37831
|
+
...this.deps.backgroundObserver === void 0 ? {} : { backgroundObserver: this.deps.backgroundObserver }
|
|
37745
37832
|
}, {
|
|
37746
37833
|
cfg,
|
|
37747
37834
|
bin,
|
|
@@ -38897,6 +38984,7 @@ const HELP$1 = [
|
|
|
38897
38984
|
"- `/agy agent [name|off]` — select default custom Markdown agent (`--agent`)",
|
|
38898
38985
|
"- `/agy settings [show|<json-or-path>|clear]` — set per-session `agy --settings` override",
|
|
38899
38986
|
"- `/agy transport [cli|acp|status]` — switch between CLI `-p` and persistent `agy acp`",
|
|
38987
|
+
"- `/agy wakeup [on|off|status]` — toggle cross-turn background timer/task wakeup or inspect active watches",
|
|
38900
38988
|
"- `/agy effort <low|medium|high|xhigh|max|default>` — default reasoning effort",
|
|
38901
38989
|
"- `/agy dispatch [minutes|off]` — credential-slot wait cap per attempt (omit to inspect; `off` = unlimited)",
|
|
38902
38990
|
"- `/agy dispatch-retries <n>` — extra dispatch attempts after the cap",
|
|
@@ -38947,6 +39035,10 @@ async function renderStatus(deps) {
|
|
|
38947
39035
|
const s = deps.acpStatus();
|
|
38948
39036
|
return ` (${s.activeProcesses} proc, ${s.sessions} session(s))`;
|
|
38949
39037
|
})() : ""),
|
|
39038
|
+
"- background wakeup: " + (cfg.backgroundWakeup ? "on" : "off") + (deps.backgroundStatus ? (() => {
|
|
39039
|
+
const w = deps.backgroundStatus();
|
|
39040
|
+
return ` (watches: ${w.activeWatches}, timers: ${w.pendingTimers}, tasks: ${w.pendingTasks})`;
|
|
39041
|
+
})() : ""),
|
|
38950
39042
|
...cfg.agent.trim() !== "" ? ["- agent: " + cfg.agent.trim()] : [],
|
|
38951
39043
|
...cfg.agySettings.trim() !== "" ? ["- settings override: " + cfg.agySettings.trim()] : "",
|
|
38952
39044
|
"- workspace: " + (cfg.workspaceRoot !== "" ? cfg.workspaceRoot : "(session cwd / process cwd)"),
|
|
@@ -39331,6 +39423,18 @@ function handleConfig$1(deps, ctx) {
|
|
|
39331
39423
|
deps.setOverride("transport", mode);
|
|
39332
39424
|
return ok$1(`Transport set to **${mode}** — effective next turn.`);
|
|
39333
39425
|
}
|
|
39426
|
+
if (sub === "wakeup") {
|
|
39427
|
+
const cur = deps.cfg().backgroundWakeup;
|
|
39428
|
+
if (arg === "" || arg === "status") {
|
|
39429
|
+
const st = deps.backgroundStatus?.();
|
|
39430
|
+
const extra = st ? ` (watches: ${st.activeWatches}, timers: ${st.pendingTimers}, tasks: ${st.pendingTasks})` : "";
|
|
39431
|
+
return ok$1(`Cross-turn background wakeup: **${cur ? "on" : "off"}**${extra} (usage: /agy wakeup <on|off|status>)`);
|
|
39432
|
+
}
|
|
39433
|
+
const val = arg.toLowerCase();
|
|
39434
|
+
if (val !== "on" && val !== "off") return err$1("usage: /agy wakeup <on|off|status>");
|
|
39435
|
+
deps.setOverride("backgroundWakeup", val === "on");
|
|
39436
|
+
return ok$1(`Cross-turn background wakeup set to **${val}**.`);
|
|
39437
|
+
}
|
|
39334
39438
|
if (sub === "effort") {
|
|
39335
39439
|
if (arg === "") return ok$1(`Current default effort: **${deps.cfg().defaultEffort || "model default"}** (usage: /agy effort <${REASONING_EFFORTS.join("|")}|default>)`);
|
|
39336
39440
|
const normalized = arg.toLowerCase();
|
|
@@ -40307,6 +40411,7 @@ const COMMAND_REGISTRY = [
|
|
|
40307
40411
|
"agent",
|
|
40308
40412
|
"settings",
|
|
40309
40413
|
"transport",
|
|
40414
|
+
"wakeup",
|
|
40310
40415
|
"effort",
|
|
40311
40416
|
"dispatch",
|
|
40312
40417
|
"dispatch-retries",
|
|
@@ -40370,7 +40475,7 @@ function agyCommandDefinition(deps) {
|
|
|
40370
40475
|
return {
|
|
40371
40476
|
name: "agy",
|
|
40372
40477
|
description: "Antigravity (agy CLI) bridge: status, login, models, mode, diagnostics, goal",
|
|
40373
|
-
input: { hint: "<status|pool|use|enable-account|disable-account|image|goal|session|btw|fork|grill|learn|compact|mcp|plugins|agents|skills|sync-ecosystem|models|mode|sandbox|agent|settings|transport|effort|dispatch|dispatch-retries|parallel|max-concurrent|workspace|clear|doctor|help>" },
|
|
40478
|
+
input: { hint: "<status|pool|use|enable-account|disable-account|image|goal|session|btw|fork|grill|learn|compact|mcp|plugins|agents|skills|sync-ecosystem|models|mode|sandbox|agent|settings|transport|wakeup|effort|dispatch|dispatch-retries|parallel|max-concurrent|workspace|clear|doctor|help>" },
|
|
40374
40479
|
handler: (invocation) => handle$1(deps, invocation.rawInput, invocation)
|
|
40375
40480
|
};
|
|
40376
40481
|
}
|
|
@@ -45985,6 +46090,7 @@ function createAcpStreamState() {
|
|
|
45985
46090
|
thoughtSeq: 0,
|
|
45986
46091
|
accumulatedText: "",
|
|
45987
46092
|
lastUsage: {},
|
|
46093
|
+
lastContextUsed: 0,
|
|
45988
46094
|
toolArgsByCallId: /* @__PURE__ */ new Map()
|
|
45989
46095
|
};
|
|
45990
46096
|
}
|
|
@@ -46061,7 +46167,11 @@ function acpUpdateToAgyEvents(sessionId, update, state) {
|
|
|
46061
46167
|
}
|
|
46062
46168
|
if (kind === "usage_update") {
|
|
46063
46169
|
const used = num(update.used);
|
|
46064
|
-
if (used !== void 0) state.
|
|
46170
|
+
if (used !== void 0) state.lastContextUsed = used;
|
|
46171
|
+
const cachedRead = num(update.cachedReadTokens) ?? num(update.cache_read_tokens) ?? num(update.cached_read_tokens);
|
|
46172
|
+
const outputTokens = num(update.outputTokens) ?? num(update.output_tokens);
|
|
46173
|
+
if (cachedRead !== void 0) state.lastUsage.cache_read_tokens = cachedRead;
|
|
46174
|
+
if (outputTokens !== void 0) state.lastUsage.output_tokens = outputTokens;
|
|
46065
46175
|
return [];
|
|
46066
46176
|
}
|
|
46067
46177
|
if (kind === "tool_call" || kind === "tool_call_update") {
|
|
@@ -46236,6 +46346,30 @@ var AcpProcess = class extends EventEmitter {
|
|
|
46236
46346
|
get stderr() {
|
|
46237
46347
|
return this.stderrTail;
|
|
46238
46348
|
}
|
|
46349
|
+
hasOpenSession(sessionId) {
|
|
46350
|
+
return this.openSessions.has(sessionId);
|
|
46351
|
+
}
|
|
46352
|
+
/**
|
|
46353
|
+
* Listen to what a session pushes outside a `session/prompt` call.
|
|
46354
|
+
*
|
|
46355
|
+
* This is how a detached background job started by a finished turn reports
|
|
46356
|
+
* its outcome: the turn already returned, so there is no prompt loop left to
|
|
46357
|
+
* receive the `session/update` notification.
|
|
46358
|
+
*/
|
|
46359
|
+
subscribeSession(sessionId, listener) {
|
|
46360
|
+
let set = this.sessionListeners.get(sessionId);
|
|
46361
|
+
if (!set) {
|
|
46362
|
+
set = /* @__PURE__ */ new Set();
|
|
46363
|
+
this.sessionListeners.set(sessionId, set);
|
|
46364
|
+
}
|
|
46365
|
+
set.add(listener);
|
|
46366
|
+
return () => {
|
|
46367
|
+
const current = this.sessionListeners.get(sessionId);
|
|
46368
|
+
if (!current) return;
|
|
46369
|
+
current.delete(listener);
|
|
46370
|
+
if (current.size === 0) this.sessionListeners.delete(sessionId);
|
|
46371
|
+
};
|
|
46372
|
+
}
|
|
46239
46373
|
ensureStarted() {
|
|
46240
46374
|
if (this.child !== null) return;
|
|
46241
46375
|
const env = withAgyQuietEnv(this.opts.env ?? process.env);
|
|
@@ -46555,6 +46689,11 @@ var AcpProcess = class extends EventEmitter {
|
|
|
46555
46689
|
var AcpSessionPool = class {
|
|
46556
46690
|
opts;
|
|
46557
46691
|
procs = /* @__PURE__ */ new Map();
|
|
46692
|
+
/**
|
|
46693
|
+
* Sessions pinned by a live background watch. Reference counted so two
|
|
46694
|
+
* watchers on the same session cannot release each other's pin.
|
|
46695
|
+
*/
|
|
46696
|
+
retainedSessions = /* @__PURE__ */ new Map();
|
|
46558
46697
|
maxProcesses;
|
|
46559
46698
|
idleTtlMs;
|
|
46560
46699
|
sweepTimer = null;
|
|
@@ -46628,9 +46767,29 @@ var AcpSessionPool = class {
|
|
|
46628
46767
|
this.stopSweepTimerIfEmpty();
|
|
46629
46768
|
return evicted;
|
|
46630
46769
|
}
|
|
46770
|
+
/** Pin a session so the idle sweeper leaves its process alone; returns the release. */
|
|
46771
|
+
retainSession(sessionId) {
|
|
46772
|
+
if (sessionId === "") return () => {};
|
|
46773
|
+
this.retainedSessions.set(sessionId, (this.retainedSessions.get(sessionId) ?? 0) + 1);
|
|
46774
|
+
let released = false;
|
|
46775
|
+
return () => {
|
|
46776
|
+
if (released) return;
|
|
46777
|
+
released = true;
|
|
46778
|
+
const cur = this.retainedSessions.get(sessionId) ?? 0;
|
|
46779
|
+
if (cur <= 1) this.retainedSessions.delete(sessionId);
|
|
46780
|
+
else this.retainedSessions.set(sessionId, cur - 1);
|
|
46781
|
+
};
|
|
46782
|
+
}
|
|
46783
|
+
/** True when this process hosts a pinned session (its background job is still running). */
|
|
46784
|
+
hasRetainedSession(proc) {
|
|
46785
|
+
if (this.retainedSessions.size === 0) return false;
|
|
46786
|
+
if (typeof proc.hasOpenSession !== "function") return false;
|
|
46787
|
+
for (const sid of this.retainedSessions.keys()) if (proc.hasOpenSession(sid)) return true;
|
|
46788
|
+
return false;
|
|
46789
|
+
}
|
|
46631
46790
|
evictIdle(now = Date.now()) {
|
|
46632
46791
|
let evicted = 0;
|
|
46633
|
-
for (const [k, p] of [...this.procs.entries()]) if (!p.isAlive() || now - p.lastUsedAt > this.idleTtlMs) {
|
|
46792
|
+
for (const [k, p] of [...this.procs.entries()]) if (!p.isAlive() || now - p.lastUsedAt > this.idleTtlMs && !this.hasRetainedSession(p)) {
|
|
46634
46793
|
this.procs.delete(k);
|
|
46635
46794
|
p.close();
|
|
46636
46795
|
evicted++;
|
|
@@ -46847,6 +47006,17 @@ async function driveAcpPrompt(opts) {
|
|
|
46847
47006
|
slot.releaseOnce();
|
|
46848
47007
|
deps.clearInFlightPrompt(sessionKey, input.prompt);
|
|
46849
47008
|
recorder.rec.settle(terminalFailure);
|
|
47009
|
+
if (!input.isAux && sessionKey !== "") deps.backgroundObserver?.onAttemptSettled?.({
|
|
47010
|
+
sessionKey,
|
|
47011
|
+
conversationId: sid,
|
|
47012
|
+
...recorder.rec.accountHome === void 0 ? {} : { accountHome: recorder.rec.accountHome },
|
|
47013
|
+
transport: "acp",
|
|
47014
|
+
recording: recorder.rec,
|
|
47015
|
+
failure: terminalFailure,
|
|
47016
|
+
superseded: deps.isSuperseded(sessionKey, recorder.rec),
|
|
47017
|
+
acpProcess: proc,
|
|
47018
|
+
acpSessionId: sid
|
|
47019
|
+
});
|
|
46850
47020
|
}
|
|
46851
47021
|
}
|
|
46852
47022
|
async function settleEarlyAbort(deps, input, slot, sid, message) {
|
|
@@ -46962,6 +47132,764 @@ async function runAcpAttempt(pool, deps, input, slot) {
|
|
|
46962
47132
|
return recorder.rec;
|
|
46963
47133
|
}
|
|
46964
47134
|
//#endregion
|
|
47135
|
+
//#region src/features/background/brain-poll.ts
|
|
47136
|
+
const TERMINAL_LOG_RE = /(?:The command exited with code \d+|Command exited with code \d+|\[exit code \d+\]|\[command timed out)/i;
|
|
47137
|
+
const TASK_SENDER_RE = /(?:^|\/)task-(\d+)$/;
|
|
47138
|
+
const TASK_LOG_URI_RE = /Log:\s*file:\/\/([^\s]+)/i;
|
|
47139
|
+
const TASK_RESULT_RE = /finished with (?:result|status):?\s*([^\n]{0,160})/i;
|
|
47140
|
+
/**
|
|
47141
|
+
* The language server emits this when it restarts, not when a job finished.
|
|
47142
|
+
* Waking the session for it would be a false positive the user cannot act on,
|
|
47143
|
+
* so it is deliberately ignored (see the counter-example test).
|
|
47144
|
+
*/
|
|
47145
|
+
const SERVER_STOP_NOTICE_RE = /stopped due to server restart/i;
|
|
47146
|
+
function rawContent(rawObj) {
|
|
47147
|
+
if (!rawObj || typeof rawObj !== "object") return "";
|
|
47148
|
+
const content = rawObj.content;
|
|
47149
|
+
return typeof content === "string" ? content : "";
|
|
47150
|
+
}
|
|
47151
|
+
function readTailText(filePath) {
|
|
47152
|
+
try {
|
|
47153
|
+
const st = statSync(filePath);
|
|
47154
|
+
if (!st.isFile() || st.size === 0) return "";
|
|
47155
|
+
const raw = readFileSync(filePath, "utf8");
|
|
47156
|
+
return raw.length <= 4096 ? raw : raw.slice(-4096);
|
|
47157
|
+
} catch {
|
|
47158
|
+
return "";
|
|
47159
|
+
}
|
|
47160
|
+
}
|
|
47161
|
+
function listSubagentStates(brainDir) {
|
|
47162
|
+
const dir = join(brainDir, ".system_generated", "subagents");
|
|
47163
|
+
const out = /* @__PURE__ */ new Map();
|
|
47164
|
+
if (!existsSync(dir)) return out;
|
|
47165
|
+
try {
|
|
47166
|
+
for (const file of readdirSync(dir)) {
|
|
47167
|
+
if (!file.endsWith(".json")) continue;
|
|
47168
|
+
try {
|
|
47169
|
+
const parsed = JSON.parse(readFileSync(join(dir, file), "utf8"));
|
|
47170
|
+
const id = typeof parsed.conversationId === "string" && parsed.conversationId !== "" ? parsed.conversationId : file.slice(0, -5);
|
|
47171
|
+
const state = typeof parsed.state === "string" ? parsed.state : "";
|
|
47172
|
+
out.set(id, state);
|
|
47173
|
+
} catch {}
|
|
47174
|
+
}
|
|
47175
|
+
} catch {}
|
|
47176
|
+
return out;
|
|
47177
|
+
}
|
|
47178
|
+
/**
|
|
47179
|
+
* Pull the detached task id out of a completion message.
|
|
47180
|
+
*
|
|
47181
|
+
* Real agy sends the outcome as a message from `<conversation>/task-<n>` with
|
|
47182
|
+
* "Task id ... finished with result: Command exited with code 0." in the body,
|
|
47183
|
+
* and the matching `tasks/task-<n>.log` only contains the command's own output.
|
|
47184
|
+
* Reading the sender is therefore what tells us a background job finished; the
|
|
47185
|
+
* log file is just where the output is.
|
|
47186
|
+
*/
|
|
47187
|
+
function taskIdFromMessage(rawObj) {
|
|
47188
|
+
if (!rawObj || typeof rawObj !== "object") return void 0;
|
|
47189
|
+
const sender = rawObj.sender;
|
|
47190
|
+
if (typeof sender === "string") {
|
|
47191
|
+
const m = TASK_SENDER_RE.exec(sender.trim());
|
|
47192
|
+
if (m?.[1]) return `task-${m[1]}`;
|
|
47193
|
+
}
|
|
47194
|
+
}
|
|
47195
|
+
/** Absolute path of the task log a completion message points at, if it names one. */
|
|
47196
|
+
function taskLogFromMessage(rawObj) {
|
|
47197
|
+
if (!rawObj || typeof rawObj !== "object") return void 0;
|
|
47198
|
+
const content = rawObj.content;
|
|
47199
|
+
if (typeof content !== "string") return void 0;
|
|
47200
|
+
const raw = TASK_LOG_URI_RE.exec(content)?.[1];
|
|
47201
|
+
if (raw === void 0 || raw === "") return void 0;
|
|
47202
|
+
try {
|
|
47203
|
+
return decodeURIComponent(raw);
|
|
47204
|
+
} catch {
|
|
47205
|
+
return raw;
|
|
47206
|
+
}
|
|
47207
|
+
}
|
|
47208
|
+
function summarizeWakeMessage(rawObj, fallbackName) {
|
|
47209
|
+
if (!rawObj || typeof rawObj !== "object") return null;
|
|
47210
|
+
const obj = rawObj;
|
|
47211
|
+
const id = typeof obj.id === "string" && obj.id.trim() !== "" ? obj.id.trim() : "";
|
|
47212
|
+
const rawSender = typeof obj.sender === "string" ? obj.sender.trim() : "";
|
|
47213
|
+
const details = obj.renderDetails && typeof obj.renderDetails === "object" ? obj.renderDetails : void 0;
|
|
47214
|
+
const title = typeof details?.messageTitle === "string" ? details.messageTitle.replace(/\s+/g, " ").trim().slice(0, 120) : "";
|
|
47215
|
+
const content = typeof obj.content === "string" ? obj.content.replace(/\s+/g, " ").trim().slice(0, 240) : "";
|
|
47216
|
+
if (title === "" && content === "") return null;
|
|
47217
|
+
const text = title !== "" && content !== "" && !content.toLowerCase().includes(title.toLowerCase()) ? `${title} — ${content}` : content || title;
|
|
47218
|
+
return {
|
|
47219
|
+
dedupKey: id !== "" ? id : fallbackName,
|
|
47220
|
+
...rawSender !== "" ? { sender: rawSender } : {},
|
|
47221
|
+
text
|
|
47222
|
+
};
|
|
47223
|
+
}
|
|
47224
|
+
/**
|
|
47225
|
+
* Record everything already present so the first poll only reports what
|
|
47226
|
+
* arrived *after* the turn ended. Returns true when a subagent was still alive.
|
|
47227
|
+
*/
|
|
47228
|
+
function baselineSessionBrain(st, brainDir) {
|
|
47229
|
+
const msgBase = join(brainDir, ".system_generated", "messages");
|
|
47230
|
+
for (const dir of [msgBase, join(msgBase, "undelivered")]) {
|
|
47231
|
+
if (!existsSync(dir)) continue;
|
|
47232
|
+
try {
|
|
47233
|
+
for (const file of readdirSync(dir)) {
|
|
47234
|
+
if (!file.endsWith(".json")) continue;
|
|
47235
|
+
st.seenMessageKeys.add(file.slice(0, -5));
|
|
47236
|
+
try {
|
|
47237
|
+
const parsed = JSON.parse(readFileSync(join(dir, file), "utf8"));
|
|
47238
|
+
if (typeof parsed?.id === "string" && parsed.id.trim() !== "") st.seenMessageKeys.add(parsed.id.trim());
|
|
47239
|
+
} catch {}
|
|
47240
|
+
}
|
|
47241
|
+
} catch {}
|
|
47242
|
+
}
|
|
47243
|
+
const tasksDir = join(brainDir, ".system_generated", "tasks");
|
|
47244
|
+
if (existsSync(tasksDir)) try {
|
|
47245
|
+
for (const file of readdirSync(tasksDir)) {
|
|
47246
|
+
if (!file.endsWith(".log")) continue;
|
|
47247
|
+
const full = join(tasksDir, file);
|
|
47248
|
+
st.knownTaskLogs.set(file, {
|
|
47249
|
+
file,
|
|
47250
|
+
path: full,
|
|
47251
|
+
terminalReported: TERMINAL_LOG_RE.test(readTailText(full))
|
|
47252
|
+
});
|
|
47253
|
+
}
|
|
47254
|
+
} catch {}
|
|
47255
|
+
const subStates = listSubagentStates(brainDir);
|
|
47256
|
+
st.knownSubagents.clear();
|
|
47257
|
+
let hasAlive = false;
|
|
47258
|
+
for (const [id, state] of subStates) {
|
|
47259
|
+
st.knownSubagents.set(id, state);
|
|
47260
|
+
if (state === "" || state === "SUBAGENT_STATE_ALIVE") hasAlive = true;
|
|
47261
|
+
}
|
|
47262
|
+
return hasAlive;
|
|
47263
|
+
}
|
|
47264
|
+
/** One scan of the brain directory; reports new messages, finished tasks, and subagent transitions. */
|
|
47265
|
+
function pollSessionBrainDir(st, brainDir, onNotice) {
|
|
47266
|
+
const msgBase = join(brainDir, ".system_generated", "messages");
|
|
47267
|
+
for (const dir of [msgBase, join(msgBase, "undelivered")]) {
|
|
47268
|
+
if (!existsSync(dir)) continue;
|
|
47269
|
+
try {
|
|
47270
|
+
for (const file of readdirSync(dir).filter((f) => f.endsWith(".json")).sort()) {
|
|
47271
|
+
const stem = file.slice(0, -5);
|
|
47272
|
+
if (st.seenMessageKeys.has(stem)) continue;
|
|
47273
|
+
st.seenMessageKeys.add(stem);
|
|
47274
|
+
let parsed;
|
|
47275
|
+
try {
|
|
47276
|
+
parsed = JSON.parse(readFileSync(join(dir, file), "utf8"));
|
|
47277
|
+
} catch {
|
|
47278
|
+
continue;
|
|
47279
|
+
}
|
|
47280
|
+
const summary = summarizeWakeMessage(parsed, stem);
|
|
47281
|
+
if (!summary || st.seenMessageKeys.has(summary.dedupKey)) continue;
|
|
47282
|
+
st.seenMessageKeys.add(summary.dedupKey);
|
|
47283
|
+
if (SERVER_STOP_NOTICE_RE.test(summary.text)) return { stoppedByServer: true };
|
|
47284
|
+
const finishedTask = taskIdFromMessage(parsed);
|
|
47285
|
+
if (finishedTask !== void 0) {
|
|
47286
|
+
const wakeKey = `task-done:${finishedTask}`;
|
|
47287
|
+
const known = st.knownTaskLogs.get(`${finishedTask}.log`);
|
|
47288
|
+
if (known !== void 0) known.terminalReported = true;
|
|
47289
|
+
if (st.seenWakeKeys.has(wakeKey)) continue;
|
|
47290
|
+
st.seenWakeKeys.add(wakeKey);
|
|
47291
|
+
const result = TASK_RESULT_RE.exec(rawContent(parsed))?.[1]?.trim();
|
|
47292
|
+
const logPath = taskLogFromMessage(parsed) ?? known?.path;
|
|
47293
|
+
onNotice({
|
|
47294
|
+
kind: "task-log",
|
|
47295
|
+
label: `Task ${finishedTask} finished`,
|
|
47296
|
+
detail: result !== void 0 && result !== "" ? result : summary.text,
|
|
47297
|
+
sender: finishedTask,
|
|
47298
|
+
...logPath !== void 0 ? { logPath } : {}
|
|
47299
|
+
});
|
|
47300
|
+
continue;
|
|
47301
|
+
}
|
|
47302
|
+
const wakeKey = `msg:${summary.dedupKey}`;
|
|
47303
|
+
if (st.seenWakeKeys.has(wakeKey)) continue;
|
|
47304
|
+
st.seenWakeKeys.add(wakeKey);
|
|
47305
|
+
const sender = summary.sender;
|
|
47306
|
+
onNotice({
|
|
47307
|
+
kind: "message",
|
|
47308
|
+
label: sender ? `Message from ${sender.includes("/") ? sender.slice(sender.lastIndexOf("/") + 1) : sender}` : "Background message",
|
|
47309
|
+
detail: summary.text,
|
|
47310
|
+
...sender ? { sender } : {}
|
|
47311
|
+
});
|
|
47312
|
+
}
|
|
47313
|
+
} catch {}
|
|
47314
|
+
}
|
|
47315
|
+
const tasksDir = join(brainDir, ".system_generated", "tasks");
|
|
47316
|
+
if (existsSync(tasksDir)) try {
|
|
47317
|
+
for (const file of readdirSync(tasksDir)) {
|
|
47318
|
+
if (!file.endsWith(".log")) continue;
|
|
47319
|
+
const full = join(tasksDir, file);
|
|
47320
|
+
let entry = st.knownTaskLogs.get(file);
|
|
47321
|
+
if (!entry) {
|
|
47322
|
+
entry = {
|
|
47323
|
+
file,
|
|
47324
|
+
path: full,
|
|
47325
|
+
terminalReported: false
|
|
47326
|
+
};
|
|
47327
|
+
st.knownTaskLogs.set(file, entry);
|
|
47328
|
+
}
|
|
47329
|
+
if (entry.terminalReported) continue;
|
|
47330
|
+
const match = TERMINAL_LOG_RE.exec(readTailText(full));
|
|
47331
|
+
if (!match) continue;
|
|
47332
|
+
entry.terminalReported = true;
|
|
47333
|
+
const taskId = file.slice(0, -4);
|
|
47334
|
+
const wakeKey = `task-exit:${taskId}`;
|
|
47335
|
+
if (!st.seenWakeKeys.has(wakeKey)) {
|
|
47336
|
+
st.seenWakeKeys.add(wakeKey);
|
|
47337
|
+
onNotice({
|
|
47338
|
+
kind: "task-log",
|
|
47339
|
+
label: `Task ${taskId} finished`,
|
|
47340
|
+
detail: match[0],
|
|
47341
|
+
sender: taskId,
|
|
47342
|
+
logPath: full
|
|
47343
|
+
});
|
|
47344
|
+
}
|
|
47345
|
+
}
|
|
47346
|
+
} catch {}
|
|
47347
|
+
for (const [subId, newState] of listSubagentStates(brainDir)) {
|
|
47348
|
+
const prev = st.knownSubagents.get(subId);
|
|
47349
|
+
st.knownSubagents.set(subId, newState);
|
|
47350
|
+
if ((prev === void 0 || prev === "" || prev === "SUBAGENT_STATE_ALIVE") && newState !== "" && newState !== "SUBAGENT_STATE_ALIVE") {
|
|
47351
|
+
const wakeKey = `sub-state:${subId}:${newState}`;
|
|
47352
|
+
if (!st.seenWakeKeys.has(wakeKey)) {
|
|
47353
|
+
st.seenWakeKeys.add(wakeKey);
|
|
47354
|
+
onNotice({
|
|
47355
|
+
kind: "subagent",
|
|
47356
|
+
label: `Subagent ${subId}`,
|
|
47357
|
+
detail: `Subagent transitioned to ${newState}`,
|
|
47358
|
+
sender: subId
|
|
47359
|
+
});
|
|
47360
|
+
}
|
|
47361
|
+
}
|
|
47362
|
+
}
|
|
47363
|
+
return { stoppedByServer: false };
|
|
47364
|
+
}
|
|
47365
|
+
//#endregion
|
|
47366
|
+
//#region src/features/background/schedule-parse.ts
|
|
47367
|
+
const BACKGROUND_TOOL_NAMES = /* @__PURE__ */ new Set([
|
|
47368
|
+
"run_command",
|
|
47369
|
+
"bash",
|
|
47370
|
+
"execute_command",
|
|
47371
|
+
"ops_bash",
|
|
47372
|
+
"sh",
|
|
47373
|
+
"shell",
|
|
47374
|
+
"invoke_subagent",
|
|
47375
|
+
"run_workflow",
|
|
47376
|
+
"swarm"
|
|
47377
|
+
]);
|
|
47378
|
+
function numArg(input, ...keys) {
|
|
47379
|
+
for (const k of keys) {
|
|
47380
|
+
const raw = input[k];
|
|
47381
|
+
if (typeof raw === "number" && Number.isFinite(raw)) return raw;
|
|
47382
|
+
if (typeof raw === "string" && raw.trim() !== "") {
|
|
47383
|
+
const n = Number(raw.trim());
|
|
47384
|
+
if (Number.isFinite(n)) return n;
|
|
47385
|
+
}
|
|
47386
|
+
}
|
|
47387
|
+
}
|
|
47388
|
+
function clipText(text, maxChars) {
|
|
47389
|
+
const flat = text.replace(/\r/g, "").replace(/\s+/g, " ").trim();
|
|
47390
|
+
if (flat.length <= maxChars) return flat;
|
|
47391
|
+
return flat.slice(0, Math.max(0, maxChars - 1)) + "…";
|
|
47392
|
+
}
|
|
47393
|
+
/**
|
|
47394
|
+
* True when the call had not finished when the turn ended — the signal that it
|
|
47395
|
+
* was handed off to the background.
|
|
47396
|
+
*
|
|
47397
|
+
* `RUNNING` is what the CLI transport reports. The ACP transport only knows
|
|
47398
|
+
* pending / in_progress / completed, and it maps a live call to `ACTIVE`, so a
|
|
47399
|
+
* live state in either vocabulary counts. A call that already reported a
|
|
47400
|
+
* terminal state is never treated as background, however live it looked earlier
|
|
47401
|
+
* in the same turn.
|
|
47402
|
+
*/
|
|
47403
|
+
function isStillLive(state) {
|
|
47404
|
+
if (state === void 0 || state === "") return false;
|
|
47405
|
+
const s = state.toLowerCase();
|
|
47406
|
+
return s === "running" || s === "active" || s === "pending" || s === "in_progress";
|
|
47407
|
+
}
|
|
47408
|
+
/** Cheap pre-filter: could this call plausibly start a background job? */
|
|
47409
|
+
function hasBackgroundTaskHint(input, ev) {
|
|
47410
|
+
if (typeof input.bgTaskId === "string") return true;
|
|
47411
|
+
const text = typeof ev.tool?.output === "string" ? ev.tool.output : ev.text;
|
|
47412
|
+
if (/\b(task-\d+)\b/i.test(text)) return true;
|
|
47413
|
+
try {
|
|
47414
|
+
return /\b(task-\d+)\b/i.test(JSON.stringify(input));
|
|
47415
|
+
} catch {
|
|
47416
|
+
return false;
|
|
47417
|
+
}
|
|
47418
|
+
}
|
|
47419
|
+
/**
|
|
47420
|
+
* Background work still pending after the turn ended.
|
|
47421
|
+
*
|
|
47422
|
+
* Recurring `CronExpression` schedules are reported as `ignoredRecurringCron`
|
|
47423
|
+
* instead of being armed: a CLI `-p` turn owns that timer, so it dies with the
|
|
47424
|
+
* process and cannot be re-armed from here.
|
|
47425
|
+
*/
|
|
47426
|
+
function extractAttemptBackgroundSignals(rec, now = Date.now()) {
|
|
47427
|
+
const schedules = [];
|
|
47428
|
+
const backgroundTools = [];
|
|
47429
|
+
let ignoredRecurringCron = false;
|
|
47430
|
+
const scheduleCandidates = [];
|
|
47431
|
+
const toolCalls = /* @__PURE__ */ new Map();
|
|
47432
|
+
for (let i = 0; i < rec.length; i++) {
|
|
47433
|
+
const ev = rec.eventAt(i);
|
|
47434
|
+
if (!ev || ev.kind !== "step" || ev.stepKind !== "tool" || !ev.tool) continue;
|
|
47435
|
+
const unwrapped = unwrapMcpTool(ev.tool.name, ev.tool.args);
|
|
47436
|
+
const name = unwrapped.tool.toLowerCase();
|
|
47437
|
+
const input = unwrapped.input;
|
|
47438
|
+
const evTs = rec.eventTimestampAt?.(i) ?? now;
|
|
47439
|
+
if (name === "schedule") {
|
|
47440
|
+
const cron = pick(input, "CronExpression", "cron_expression");
|
|
47441
|
+
const duration = numArg(input, "DurationSeconds", "duration_seconds");
|
|
47442
|
+
const prompt = pick(input, "Prompt", "prompt") ?? "Check scheduled task progress and continue.";
|
|
47443
|
+
const cond = pick(input, "TimerCondition", "timer_condition") ?? "never";
|
|
47444
|
+
if (cron && (!duration || duration <= 0)) {
|
|
47445
|
+
ignoredRecurringCron = true;
|
|
47446
|
+
continue;
|
|
47447
|
+
}
|
|
47448
|
+
if (duration !== void 0 && duration > 0 && !isTerminalState(ev.state)) scheduleCandidates.push({
|
|
47449
|
+
index: i,
|
|
47450
|
+
ts: evTs,
|
|
47451
|
+
item: {
|
|
47452
|
+
stepKey: ev.stepKey,
|
|
47453
|
+
delayMs: Math.max(500, Math.round(duration * 1e3)),
|
|
47454
|
+
durationSeconds: duration,
|
|
47455
|
+
prompt: clipText(prompt, 500),
|
|
47456
|
+
timerCondition: cond,
|
|
47457
|
+
...cron ? { cronExpression: cron } : {}
|
|
47458
|
+
}
|
|
47459
|
+
});
|
|
47460
|
+
continue;
|
|
47461
|
+
}
|
|
47462
|
+
if (BACKGROUND_TOOL_NAMES.has(name) || hasBackgroundTaskHint(input, ev)) toolCalls.set(ev.stepKey, {
|
|
47463
|
+
toolName: unwrapped.tool,
|
|
47464
|
+
name,
|
|
47465
|
+
input,
|
|
47466
|
+
event: ev
|
|
47467
|
+
});
|
|
47468
|
+
}
|
|
47469
|
+
for (const call of toolCalls.values()) {
|
|
47470
|
+
if (!isStillLive(call.event.state)) continue;
|
|
47471
|
+
const output = typeof call.event.tool?.output === "string" ? call.event.tool.output : call.event.text;
|
|
47472
|
+
const taskId = (/\b(task-\d+)\b/i.exec(output) ?? /\b(task-\d+)\b/i.exec(JSON.stringify(call.input)))?.[1] ?? (typeof call.input.bgTaskId === "string" ? call.input.bgTaskId : void 0);
|
|
47473
|
+
if (!BACKGROUND_TOOL_NAMES.has(call.name) && taskId === void 0) continue;
|
|
47474
|
+
const cmd = pick(call.input, "CommandLine", "command_line", "command", "cmd", "Role", "role", "Description", "description");
|
|
47475
|
+
backgroundTools.push({
|
|
47476
|
+
stepKey: call.event.stepKey,
|
|
47477
|
+
toolName: call.toolName,
|
|
47478
|
+
...taskId ? { taskId } : {},
|
|
47479
|
+
summary: cmd ? clipText(cmd, 120) : taskId ?? call.toolName
|
|
47480
|
+
});
|
|
47481
|
+
}
|
|
47482
|
+
for (const cand of scheduleCandidates) {
|
|
47483
|
+
const elapsed = Math.max(0, now - cand.ts);
|
|
47484
|
+
let sawSubstantialLaterWork = false;
|
|
47485
|
+
for (let j = cand.index + 1; j < rec.length; j++) {
|
|
47486
|
+
const later = rec.eventAt(j);
|
|
47487
|
+
if (!later || later.kind !== "step") continue;
|
|
47488
|
+
if (later.stepKind === "tool" && later.tool?.name.toLowerCase() !== "schedule") {
|
|
47489
|
+
sawSubstantialLaterWork = true;
|
|
47490
|
+
break;
|
|
47491
|
+
}
|
|
47492
|
+
const laterText = later.stepKind === "subagent" ? later.text : "";
|
|
47493
|
+
if (laterText.includes("[后台通知") && laterText.toLowerCase().includes(cand.item.stepKey.toLowerCase())) {
|
|
47494
|
+
sawSubstantialLaterWork = true;
|
|
47495
|
+
break;
|
|
47496
|
+
}
|
|
47497
|
+
}
|
|
47498
|
+
if (sawSubstantialLaterWork && elapsed >= cand.item.delayMs) continue;
|
|
47499
|
+
const remainingMs = Math.max(500, cand.item.delayMs - elapsed);
|
|
47500
|
+
schedules.push({
|
|
47501
|
+
...cand.item,
|
|
47502
|
+
delayMs: remainingMs
|
|
47503
|
+
});
|
|
47504
|
+
}
|
|
47505
|
+
return {
|
|
47506
|
+
schedules,
|
|
47507
|
+
backgroundTools,
|
|
47508
|
+
ignoredRecurringCron
|
|
47509
|
+
};
|
|
47510
|
+
}
|
|
47511
|
+
function isTerminalState(state) {
|
|
47512
|
+
if (state === void 0) return false;
|
|
47513
|
+
const s = state.toLowerCase();
|
|
47514
|
+
return s === "done" || s === "error" || s === "canceled" || s === "cancelled" || s === "failed";
|
|
47515
|
+
}
|
|
47516
|
+
function matchesTimerCondition(condition, sender) {
|
|
47517
|
+
const cond = condition.trim();
|
|
47518
|
+
if (cond === "" || cond.toLowerCase() === "never") return false;
|
|
47519
|
+
if (cond.toLowerCase() === "any") return true;
|
|
47520
|
+
if (!sender) return false;
|
|
47521
|
+
const normSender = sender.trim().toLowerCase();
|
|
47522
|
+
const normCond = cond.toLowerCase();
|
|
47523
|
+
return normSender === normCond || normSender.endsWith("/" + normCond) || normSender.includes(normCond);
|
|
47524
|
+
}
|
|
47525
|
+
function buildWakeupMessageText(items) {
|
|
47526
|
+
const first = items[0];
|
|
47527
|
+
const summary = items.length === 1 && first ? clipText(`${first.label}: ${first.detail}`, 115) : clipText(`${items.length} background task updates (${first?.label ?? "agy"})`, 115);
|
|
47528
|
+
const lines = [
|
|
47529
|
+
"[Background Task Wakeup · dsh-agy-link]",
|
|
47530
|
+
"One or more background activities or scheduled timers for this Antigravity session triggered after the previous turn ended:",
|
|
47531
|
+
""
|
|
47532
|
+
];
|
|
47533
|
+
for (const item of items) {
|
|
47534
|
+
lines.push(`- [${item.kind}] ${item.label}: ${item.detail}`);
|
|
47535
|
+
if (item.logPath) lines.push(` Log: ${item.logPath}`);
|
|
47536
|
+
}
|
|
47537
|
+
lines.push("", "Please inspect the updated state/output, execute any follow-up action requested by the scheduled task or finished job, and report the result concisely. Do not claim completion if the task is still incomplete or failed.");
|
|
47538
|
+
return {
|
|
47539
|
+
summary,
|
|
47540
|
+
text: lines.join("\n")
|
|
47541
|
+
};
|
|
47542
|
+
}
|
|
47543
|
+
//#endregion
|
|
47544
|
+
//#region src/features/background/watcher.ts
|
|
47545
|
+
var BackgroundWakeWatcher = class {
|
|
47546
|
+
opts;
|
|
47547
|
+
sessions = /* @__PURE__ */ new Map();
|
|
47548
|
+
pollTimer = null;
|
|
47549
|
+
disposed = false;
|
|
47550
|
+
pollIntervalMs;
|
|
47551
|
+
coalesceMs;
|
|
47552
|
+
constructor(opts) {
|
|
47553
|
+
this.opts = opts;
|
|
47554
|
+
this.pollIntervalMs = Math.max(50, opts.pollIntervalMs ?? 2500);
|
|
47555
|
+
this.coalesceMs = Math.max(20, opts.coalesceMs ?? 350);
|
|
47556
|
+
}
|
|
47557
|
+
getOrCreateSession(sessionKey) {
|
|
47558
|
+
let st = this.sessions.get(sessionKey);
|
|
47559
|
+
if (!st) {
|
|
47560
|
+
st = {
|
|
47561
|
+
sessionKey,
|
|
47562
|
+
generation: 0,
|
|
47563
|
+
wakesUsed: 0,
|
|
47564
|
+
activeTurn: false,
|
|
47565
|
+
expiresAt: 0,
|
|
47566
|
+
brainDir: null,
|
|
47567
|
+
hasActiveTasks: false,
|
|
47568
|
+
seenMessageKeys: /* @__PURE__ */ new Set(),
|
|
47569
|
+
knownTaskLogs: /* @__PURE__ */ new Map(),
|
|
47570
|
+
knownSubagents: /* @__PURE__ */ new Map(),
|
|
47571
|
+
seenWakeKeys: /* @__PURE__ */ new Set(),
|
|
47572
|
+
schedules: /* @__PURE__ */ new Map(),
|
|
47573
|
+
acpCleanups: [],
|
|
47574
|
+
pendingNotices: [],
|
|
47575
|
+
coalesceTimer: null,
|
|
47576
|
+
deferTimer: null,
|
|
47577
|
+
dispatching: false
|
|
47578
|
+
};
|
|
47579
|
+
this.sessions.set(sessionKey, st);
|
|
47580
|
+
}
|
|
47581
|
+
return st;
|
|
47582
|
+
}
|
|
47583
|
+
/** Reuse an existing state object (later slices keep the same record in a leaf module). */
|
|
47584
|
+
adopt(st) {
|
|
47585
|
+
if (this.disposed) return;
|
|
47586
|
+
const prev = this.sessions.get(st.sessionKey);
|
|
47587
|
+
if (prev !== void 0 && prev !== st) this.clearSessionWatches(prev);
|
|
47588
|
+
this.sessions.set(st.sessionKey, st);
|
|
47589
|
+
}
|
|
47590
|
+
/**
|
|
47591
|
+
* Feed one background notice into a session's queue.
|
|
47592
|
+
*
|
|
47593
|
+
* Used by the TimerCondition cancel path and by the tests; slice 3 calls it
|
|
47594
|
+
* from the ACP post-turn watcher.
|
|
47595
|
+
*/
|
|
47596
|
+
noteNotice(sessionKey, item) {
|
|
47597
|
+
if (this.disposed || sessionKey === "") return;
|
|
47598
|
+
const cfg = this.opts.getConfig();
|
|
47599
|
+
if (!cfg.enabled || !cfg.backgroundWakeup) return;
|
|
47600
|
+
const st = this.getOrCreateSession(sessionKey);
|
|
47601
|
+
this.enqueueWake(st, item);
|
|
47602
|
+
}
|
|
47603
|
+
onHumanTurn(sessionKey) {
|
|
47604
|
+
if (this.disposed || sessionKey === "") return;
|
|
47605
|
+
const st = this.sessions.get(sessionKey);
|
|
47606
|
+
if (!st) return;
|
|
47607
|
+
st.generation += 1;
|
|
47608
|
+
st.wakesUsed = 0;
|
|
47609
|
+
this.clearSessionWatches(st);
|
|
47610
|
+
}
|
|
47611
|
+
onAttemptStart(sessionKey) {
|
|
47612
|
+
if (this.disposed || sessionKey === "") return;
|
|
47613
|
+
const st = this.getOrCreateSession(sessionKey);
|
|
47614
|
+
st.activeTurn = true;
|
|
47615
|
+
if (st.deferTimer !== null) {
|
|
47616
|
+
clearTimeout(st.deferTimer);
|
|
47617
|
+
st.deferTimer = null;
|
|
47618
|
+
}
|
|
47619
|
+
}
|
|
47620
|
+
onAttemptSettled(info) {
|
|
47621
|
+
if (this.disposed || info.sessionKey === "") return;
|
|
47622
|
+
const st = this.getOrCreateSession(info.sessionKey);
|
|
47623
|
+
st.activeTurn = false;
|
|
47624
|
+
const cfg = this.opts.getConfig();
|
|
47625
|
+
if (!cfg.enabled || !cfg.backgroundWakeup) return;
|
|
47626
|
+
if (this.opts.isArchived?.(info.sessionKey)) {
|
|
47627
|
+
this.clearSessionWatches(st);
|
|
47628
|
+
return;
|
|
47629
|
+
}
|
|
47630
|
+
if (info.superseded || info.failure !== null) return;
|
|
47631
|
+
const signals = extractAttemptBackgroundSignals(info.recording);
|
|
47632
|
+
if (signals.ignoredRecurringCron && info.transport === "cli") this.opts.log?.(`[background-wakeup] session=${info.sessionKey}: recurring cron schedule does not persist across CLI -p exit; use one-shot DurationSeconds or ACP transport`);
|
|
47633
|
+
const ttlMs = Math.max(1, cfg.backgroundWakeupTtlMinutes) * 6e4;
|
|
47634
|
+
const brainDir = info.conversationId ? findBrainDir(info.conversationId, info.accountHome) : null;
|
|
47635
|
+
if (brainDir) st.brainDir = brainDir;
|
|
47636
|
+
const aliveSubagents = brainDir ? baselineSessionBrain(st, brainDir) : false;
|
|
47637
|
+
const hasPendingTasks = signals.backgroundTools.length > 0 || aliveSubagents;
|
|
47638
|
+
const maxScheduleDelay = signals.schedules.reduce((m, s) => Math.max(m, s.delayMs), 0);
|
|
47639
|
+
const watchWindow = Math.min(ttlMs, Math.max(ttlMs, maxScheduleDelay + 5e3));
|
|
47640
|
+
if (signals.schedules.length === 0 && !hasPendingTasks) {
|
|
47641
|
+
if (st.schedules.size === 0 && !st.hasActiveTasks) this.clearSessionWatches(st);
|
|
47642
|
+
return;
|
|
47643
|
+
}
|
|
47644
|
+
st.expiresAt = Math.max(st.expiresAt, Date.now() + watchWindow);
|
|
47645
|
+
st.hasActiveTasks = st.hasActiveTasks || hasPendingTasks;
|
|
47646
|
+
const turnGen = st.generation;
|
|
47647
|
+
for (const s of signals.schedules) this.armScheduleTimer(st, turnGen, s.stepKey, Math.min(s.delayMs, ttlMs), s.prompt, s.timerCondition, info.transport);
|
|
47648
|
+
if (info.transport === "acp" && info.acpProcess && info.acpSessionId && hasPendingTasks) this.attachAcpWatch(st, info.acpProcess, info.acpSessionId, turnGen);
|
|
47649
|
+
if (hasPendingTasks && st.brainDir) this.ensurePollLoop();
|
|
47650
|
+
}
|
|
47651
|
+
/**
|
|
47652
|
+
* ACP keeps the session alive after the turn returns, so the detached work
|
|
47653
|
+
* announces itself through `session/update` instead of a file. Listening is
|
|
47654
|
+
* the only way to know it finished without polling the process.
|
|
47655
|
+
*
|
|
47656
|
+
* The session is pinned through the pool as well: without that the idle
|
|
47657
|
+
* sweeper could close the process while its background job is still running.
|
|
47658
|
+
*/
|
|
47659
|
+
attachAcpWatch(st, proc, sid, turnGen) {
|
|
47660
|
+
this.releaseAcp(st);
|
|
47661
|
+
const unsub = proc.subscribeSession(sid, (update) => {
|
|
47662
|
+
if (this.disposed || st.generation !== turnGen || st.activeTurn) return;
|
|
47663
|
+
const kind = typeof update.sessionUpdate === "string" ? update.sessionUpdate : "";
|
|
47664
|
+
if (kind === "tool_call_update") {
|
|
47665
|
+
const status = typeof update.status === "string" ? update.status.toLowerCase() : "";
|
|
47666
|
+
if (status === "completed" || status === "failed" || status === "error" || status === "cancelled" || status === "canceled") {
|
|
47667
|
+
const title = typeof update.title === "string" && update.title !== "" ? update.title : "ACP background tool";
|
|
47668
|
+
const callId = typeof update.toolCallId === "string" ? update.toolCallId : title;
|
|
47669
|
+
const wakeKey = `acp-tool:${callId}:${status}`;
|
|
47670
|
+
if (st.seenWakeKeys.has(wakeKey)) return;
|
|
47671
|
+
st.seenWakeKeys.add(wakeKey);
|
|
47672
|
+
this.enqueueWake(st, {
|
|
47673
|
+
kind: "acp",
|
|
47674
|
+
label: `${title} (${status})`,
|
|
47675
|
+
detail: `ACP tool ${status}`,
|
|
47676
|
+
sender: callId
|
|
47677
|
+
});
|
|
47678
|
+
}
|
|
47679
|
+
} else if (kind === "agent_message_chunk") {
|
|
47680
|
+
const content = update.content;
|
|
47681
|
+
const text = typeof content?.text === "string" ? content.text.trim() : "";
|
|
47682
|
+
if (text !== "") {
|
|
47683
|
+
const wakeKey = `acp-msg:${turnGen}:${text.slice(0, 60)}`;
|
|
47684
|
+
if (st.seenWakeKeys.has(wakeKey)) return;
|
|
47685
|
+
st.seenWakeKeys.add(wakeKey);
|
|
47686
|
+
this.enqueueWake(st, {
|
|
47687
|
+
kind: "acp",
|
|
47688
|
+
label: "ACP post-turn message",
|
|
47689
|
+
detail: text.slice(0, 240)
|
|
47690
|
+
});
|
|
47691
|
+
}
|
|
47692
|
+
}
|
|
47693
|
+
});
|
|
47694
|
+
st.acpCleanups.push(unsub);
|
|
47695
|
+
if (this.opts.retainAcpSession) st.acpCleanups.push(this.opts.retainAcpSession(sid));
|
|
47696
|
+
}
|
|
47697
|
+
releaseAcp(st) {
|
|
47698
|
+
for (const fn of st.acpCleanups.splice(0, st.acpCleanups.length)) try {
|
|
47699
|
+
fn();
|
|
47700
|
+
} catch {}
|
|
47701
|
+
}
|
|
47702
|
+
armScheduleTimer(st, turnGen, key, delayMs, prompt, timerCondition, transport) {
|
|
47703
|
+
const existing = st.schedules.get(key);
|
|
47704
|
+
if (existing) clearTimeout(existing.timer);
|
|
47705
|
+
const effectiveDelay = transport === "acp" ? delayMs + 2e3 : delayMs;
|
|
47706
|
+
const timer = setTimeout(() => {
|
|
47707
|
+
st.schedules.delete(key);
|
|
47708
|
+
if (this.disposed || st.generation !== turnGen) return;
|
|
47709
|
+
const wakeKey = `sched:${key}:${turnGen}`;
|
|
47710
|
+
if (st.seenWakeKeys.has(wakeKey)) return;
|
|
47711
|
+
st.seenWakeKeys.add(wakeKey);
|
|
47712
|
+
this.enqueueWake(st, {
|
|
47713
|
+
kind: "schedule",
|
|
47714
|
+
label: "Scheduled timer",
|
|
47715
|
+
detail: prompt
|
|
47716
|
+
});
|
|
47717
|
+
}, effectiveDelay);
|
|
47718
|
+
timer.unref?.();
|
|
47719
|
+
st.schedules.set(key, {
|
|
47720
|
+
key,
|
|
47721
|
+
prompt,
|
|
47722
|
+
timerCondition,
|
|
47723
|
+
timer
|
|
47724
|
+
});
|
|
47725
|
+
}
|
|
47726
|
+
ensurePollLoop() {
|
|
47727
|
+
if (this.pollTimer !== null || this.disposed) return;
|
|
47728
|
+
this.pollTimer = setInterval(() => this.pollAll(), this.pollIntervalMs);
|
|
47729
|
+
this.pollTimer.unref?.();
|
|
47730
|
+
}
|
|
47731
|
+
stopPollLoopIfIdle() {
|
|
47732
|
+
if (!Array.from(this.sessions.values()).some((s) => s.hasActiveTasks && !s.activeTurn) && this.pollTimer !== null) {
|
|
47733
|
+
clearInterval(this.pollTimer);
|
|
47734
|
+
this.pollTimer = null;
|
|
47735
|
+
}
|
|
47736
|
+
}
|
|
47737
|
+
/** Run one scan now (tests and the `/agy wakeup` command use it). */
|
|
47738
|
+
pollNow() {
|
|
47739
|
+
this.pollAll();
|
|
47740
|
+
}
|
|
47741
|
+
pollAll() {
|
|
47742
|
+
if (this.disposed) return;
|
|
47743
|
+
const cfg = this.opts.getConfig();
|
|
47744
|
+
if (!cfg.enabled || !cfg.backgroundWakeup) return;
|
|
47745
|
+
const now = Date.now();
|
|
47746
|
+
for (const st of Array.from(this.sessions.values())) {
|
|
47747
|
+
if (this.opts.isArchived?.(st.sessionKey)) {
|
|
47748
|
+
this.clearSessionWatches(st);
|
|
47749
|
+
continue;
|
|
47750
|
+
}
|
|
47751
|
+
if (st.expiresAt > 0 && now > st.expiresAt) {
|
|
47752
|
+
this.clearSessionWatches(st);
|
|
47753
|
+
continue;
|
|
47754
|
+
}
|
|
47755
|
+
if (!st.hasActiveTasks || st.activeTurn || !st.brainDir) continue;
|
|
47756
|
+
this.pollSessionBrain(st, st.brainDir);
|
|
47757
|
+
}
|
|
47758
|
+
this.stopPollLoopIfIdle();
|
|
47759
|
+
}
|
|
47760
|
+
pollSessionBrain(st, brainDir) {
|
|
47761
|
+
if (pollSessionBrainDir(st, brainDir, (item) => this.enqueueWake(st, item)).stoppedByServer) {
|
|
47762
|
+
st.hasActiveTasks = false;
|
|
47763
|
+
this.clearSessionWatches(st);
|
|
47764
|
+
}
|
|
47765
|
+
}
|
|
47766
|
+
cancelMatchingScheduleTimers(st, item) {
|
|
47767
|
+
if (item.kind === "schedule") return;
|
|
47768
|
+
for (const [k, s] of Array.from(st.schedules.entries())) if (matchesTimerCondition(s.timerCondition, item.sender ?? item.label)) {
|
|
47769
|
+
clearTimeout(s.timer);
|
|
47770
|
+
st.schedules.delete(k);
|
|
47771
|
+
}
|
|
47772
|
+
}
|
|
47773
|
+
enqueueWake(st, item) {
|
|
47774
|
+
if (this.disposed || this.opts.isArchived?.(st.sessionKey)) return;
|
|
47775
|
+
this.cancelMatchingScheduleTimers(st, item);
|
|
47776
|
+
st.pendingNotices.push(item);
|
|
47777
|
+
if (st.coalesceTimer !== null) return;
|
|
47778
|
+
st.coalesceTimer = setTimeout(() => {
|
|
47779
|
+
st.coalesceTimer = null;
|
|
47780
|
+
this.tryDispatch(st.sessionKey);
|
|
47781
|
+
}, this.coalesceMs);
|
|
47782
|
+
st.coalesceTimer.unref?.();
|
|
47783
|
+
}
|
|
47784
|
+
scheduleDefer(st, delayMs) {
|
|
47785
|
+
if (this.disposed || st.deferTimer !== null) return;
|
|
47786
|
+
st.deferTimer = setTimeout(() => {
|
|
47787
|
+
st.deferTimer = null;
|
|
47788
|
+
this.tryDispatch(st.sessionKey);
|
|
47789
|
+
}, delayMs);
|
|
47790
|
+
st.deferTimer.unref?.();
|
|
47791
|
+
}
|
|
47792
|
+
async tryDispatch(sessionKey) {
|
|
47793
|
+
const st = this.sessions.get(sessionKey);
|
|
47794
|
+
if (!st || this.disposed || st.dispatching || st.pendingNotices.length === 0) return;
|
|
47795
|
+
const cfg = this.opts.getConfig();
|
|
47796
|
+
if (!cfg.enabled || !cfg.backgroundWakeup || this.opts.isArchived?.(sessionKey)) {
|
|
47797
|
+
this.clearSessionWatches(st);
|
|
47798
|
+
return;
|
|
47799
|
+
}
|
|
47800
|
+
const maxWakes = Math.max(1, cfg.backgroundWakeupMaxPerSession);
|
|
47801
|
+
if (st.wakesUsed >= maxWakes) {
|
|
47802
|
+
st.pendingNotices = [];
|
|
47803
|
+
this.clearSessionWatches(st);
|
|
47804
|
+
this.opts.log?.(`[background-wakeup] session=${sessionKey}: reached max wakes (${maxWakes}); pausing until next human turn`);
|
|
47805
|
+
return;
|
|
47806
|
+
}
|
|
47807
|
+
st.dispatching = true;
|
|
47808
|
+
try {
|
|
47809
|
+
const liveRun = this.opts.getActiveRun?.(sessionKey);
|
|
47810
|
+
if (liveRun && !liveRun.isSettled) {
|
|
47811
|
+
this.scheduleDefer(st, 1500);
|
|
47812
|
+
return;
|
|
47813
|
+
}
|
|
47814
|
+
const agent = await this.opts.resolveAgent(sessionKey).catch(() => null);
|
|
47815
|
+
if (!agent || typeof agent.followup !== "function") {
|
|
47816
|
+
st.pendingNotices = [];
|
|
47817
|
+
return;
|
|
47818
|
+
}
|
|
47819
|
+
if (agent.status === "running") {
|
|
47820
|
+
if (typeof agent.whenIdle === "function") Promise.race([agent.whenIdle(), new Promise((r) => setTimeout(r, 2e3))]).then(() => this.tryDispatch(sessionKey)).catch(() => void 0);
|
|
47821
|
+
else this.scheduleDefer(st, 1500);
|
|
47822
|
+
return;
|
|
47823
|
+
}
|
|
47824
|
+
const nextTurn = agent.inbox?.nextTurn;
|
|
47825
|
+
if (Array.isArray(nextTurn) && nextTurn.some((m) => m?.source?.plugin === "agy-link" && m?.source?.form === "notice")) return;
|
|
47826
|
+
const { summary, text } = buildWakeupMessageText(st.pendingNotices.splice(0, st.pendingNotices.length));
|
|
47827
|
+
const msg = createUserMessage({
|
|
47828
|
+
content: [{
|
|
47829
|
+
type: "text",
|
|
47830
|
+
text
|
|
47831
|
+
}],
|
|
47832
|
+
source: {
|
|
47833
|
+
kind: "plugin",
|
|
47834
|
+
plugin: "agy-link",
|
|
47835
|
+
form: "notice",
|
|
47836
|
+
summary: boundContextSummary(summary)
|
|
47837
|
+
}
|
|
47838
|
+
});
|
|
47839
|
+
st.wakesUsed += 1;
|
|
47840
|
+
if (st.schedules.size === 0) st.hasActiveTasks = false;
|
|
47841
|
+
agent.followup(msg);
|
|
47842
|
+
this.opts.log?.(`[background-wakeup] woken session=${sessionKey} (${summary})`);
|
|
47843
|
+
} finally {
|
|
47844
|
+
st.dispatching = false;
|
|
47845
|
+
this.stopPollLoopIfIdle();
|
|
47846
|
+
}
|
|
47847
|
+
}
|
|
47848
|
+
clearSessionWatches(st) {
|
|
47849
|
+
st.hasActiveTasks = false;
|
|
47850
|
+
st.expiresAt = 0;
|
|
47851
|
+
st.pendingNotices = [];
|
|
47852
|
+
for (const s of st.schedules.values()) clearTimeout(s.timer);
|
|
47853
|
+
st.schedules.clear();
|
|
47854
|
+
if (st.coalesceTimer !== null) {
|
|
47855
|
+
clearTimeout(st.coalesceTimer);
|
|
47856
|
+
st.coalesceTimer = null;
|
|
47857
|
+
}
|
|
47858
|
+
if (st.deferTimer !== null) {
|
|
47859
|
+
clearTimeout(st.deferTimer);
|
|
47860
|
+
st.deferTimer = null;
|
|
47861
|
+
}
|
|
47862
|
+
this.releaseAcp(st);
|
|
47863
|
+
this.stopPollLoopIfIdle();
|
|
47864
|
+
}
|
|
47865
|
+
status() {
|
|
47866
|
+
const cfg = this.opts.getConfig();
|
|
47867
|
+
let pendingTimers = 0;
|
|
47868
|
+
let pendingTasks = 0;
|
|
47869
|
+
let activeWatches = 0;
|
|
47870
|
+
for (const st of this.sessions.values()) {
|
|
47871
|
+
if (st.schedules.size > 0 || st.hasActiveTasks) activeWatches += 1;
|
|
47872
|
+
pendingTimers += st.schedules.size;
|
|
47873
|
+
if (st.hasActiveTasks) pendingTasks += 1;
|
|
47874
|
+
}
|
|
47875
|
+
return {
|
|
47876
|
+
enabled: cfg.enabled && cfg.backgroundWakeup,
|
|
47877
|
+
activeWatches,
|
|
47878
|
+
pendingTimers,
|
|
47879
|
+
pendingTasks
|
|
47880
|
+
};
|
|
47881
|
+
}
|
|
47882
|
+
dispose() {
|
|
47883
|
+
this.disposed = true;
|
|
47884
|
+
if (this.pollTimer !== null) {
|
|
47885
|
+
clearInterval(this.pollTimer);
|
|
47886
|
+
this.pollTimer = null;
|
|
47887
|
+
}
|
|
47888
|
+
for (const st of this.sessions.values()) this.clearSessionWatches(st);
|
|
47889
|
+
this.sessions.clear();
|
|
47890
|
+
}
|
|
47891
|
+
};
|
|
47892
|
+
//#endregion
|
|
46965
47893
|
//#region src/host/service-helpers.ts
|
|
46966
47894
|
/** Cross-session concurrency limiter (ADR-12). max() <= 0 means unlimited. */
|
|
46967
47895
|
var Semaphore = class {
|
|
@@ -47202,6 +48130,13 @@ async function runTranslationStream(ctx, getConfig, log, req, workerPool) {
|
|
|
47202
48130
|
}
|
|
47203
48131
|
//#endregion
|
|
47204
48132
|
//#region src/host/services.ts
|
|
48133
|
+
function safeCtxGet(ctx, name) {
|
|
48134
|
+
try {
|
|
48135
|
+
return ctx.get(name);
|
|
48136
|
+
} catch {
|
|
48137
|
+
return;
|
|
48138
|
+
}
|
|
48139
|
+
}
|
|
47205
48140
|
function createHostServices(ctx, entryConfig = {}) {
|
|
47206
48141
|
const tag = "[dsh-agy-link] ";
|
|
47207
48142
|
const log = (msg) => {
|
|
@@ -47381,7 +48316,37 @@ function createHostServices(ctx, entryConfig = {}) {
|
|
|
47381
48316
|
cfg: getConfig,
|
|
47382
48317
|
log
|
|
47383
48318
|
});
|
|
47384
|
-
|
|
48319
|
+
let adapter;
|
|
48320
|
+
const backgroundWakeup = new BackgroundWakeWatcher({
|
|
48321
|
+
getConfig,
|
|
48322
|
+
log,
|
|
48323
|
+
getActiveRun: (sessionId) => adapter.getActiveRun(sessionId),
|
|
48324
|
+
retainAcpSession: (sid) => acpPool.retainSession(sid),
|
|
48325
|
+
isArchived: (sessionId) => {
|
|
48326
|
+
try {
|
|
48327
|
+
const archived = safeCtxGet(ctx, "workspaceRegistry")?.archivedSessionIds;
|
|
48328
|
+
if (!archived) return false;
|
|
48329
|
+
if (typeof archived.has === "function") return archived.has(sessionId);
|
|
48330
|
+
for (const id of archived) if (id === sessionId) return true;
|
|
48331
|
+
} catch {}
|
|
48332
|
+
return false;
|
|
48333
|
+
},
|
|
48334
|
+
resolveAgent: async (sessionId) => {
|
|
48335
|
+
try {
|
|
48336
|
+
const live = safeCtxGet(ctx, "agents")?.get?.(sessionId);
|
|
48337
|
+
if (live && typeof live.followup === "function") return live;
|
|
48338
|
+
const ctrl = safeCtxGet(ctx, "sessionController");
|
|
48339
|
+
if (ctrl && typeof ctrl.resolveAgent === "function") {
|
|
48340
|
+
const res = await ctrl.resolveAgent(sessionId);
|
|
48341
|
+
if (res && typeof res === "object" && res.agent && typeof res.agent.followup === "function") return res.agent;
|
|
48342
|
+
}
|
|
48343
|
+
} catch (err) {
|
|
48344
|
+
log("background-wakeup resolveAgent error: " + String(err));
|
|
48345
|
+
}
|
|
48346
|
+
return null;
|
|
48347
|
+
}
|
|
48348
|
+
});
|
|
48349
|
+
adapter = new AgyAdapter({
|
|
47385
48350
|
getConfig,
|
|
47386
48351
|
catalog,
|
|
47387
48352
|
store,
|
|
@@ -47409,7 +48374,8 @@ function createHostServices(ctx, entryConfig = {}) {
|
|
|
47409
48374
|
lastParser = p;
|
|
47410
48375
|
},
|
|
47411
48376
|
readImage: (ref) => readSessionImage(ctx, dshHome(), ref),
|
|
47412
|
-
runAcp: (attemptDeps, attemptInput, slot) => runAcpAttempt(acpPool, attemptDeps, attemptInput, slot)
|
|
48377
|
+
runAcp: (attemptDeps, attemptInput, slot) => runAcpAttempt(acpPool, attemptDeps, attemptInput, slot),
|
|
48378
|
+
backgroundObserver: backgroundWakeup
|
|
47413
48379
|
});
|
|
47414
48380
|
const translationWorkers = new TranslationWorkerPool({
|
|
47415
48381
|
cfg: getConfig,
|
|
@@ -47486,6 +48452,14 @@ function createHostServices(ctx, entryConfig = {}) {
|
|
|
47486
48452
|
} catch {}
|
|
47487
48453
|
return list;
|
|
47488
48454
|
};
|
|
48455
|
+
const imageService = new ImageService({
|
|
48456
|
+
cfg: getConfig,
|
|
48457
|
+
bin,
|
|
48458
|
+
run: (call) => runViaAdapter(adapter, call),
|
|
48459
|
+
catalog: () => catalog.get(),
|
|
48460
|
+
...quotaHooks,
|
|
48461
|
+
log
|
|
48462
|
+
});
|
|
47489
48463
|
return {
|
|
47490
48464
|
getConfig,
|
|
47491
48465
|
log,
|
|
@@ -47504,15 +48478,9 @@ function createHostServices(ctx, entryConfig = {}) {
|
|
|
47504
48478
|
runs,
|
|
47505
48479
|
adapter,
|
|
47506
48480
|
acpPool,
|
|
48481
|
+
backgroundWakeup,
|
|
47507
48482
|
ecosystem,
|
|
47508
|
-
imageService
|
|
47509
|
-
cfg: getConfig,
|
|
47510
|
-
bin,
|
|
47511
|
-
run: (call) => runViaAdapter(adapter, call),
|
|
47512
|
-
catalog: () => catalog.get(),
|
|
47513
|
-
...quotaHooks,
|
|
47514
|
-
log
|
|
47515
|
-
}),
|
|
48483
|
+
imageService,
|
|
47516
48484
|
translation,
|
|
47517
48485
|
translationWorkers,
|
|
47518
48486
|
setOverride,
|
|
@@ -47644,7 +48612,7 @@ function selectableModels(supportedModels, quotaScope) {
|
|
|
47644
48612
|
return sanitizeCatalogEntries(mergeCatalogWithQuotaModels(sanitizeCatalogEntries(supportedModels).entries, quota)).entries;
|
|
47645
48613
|
}
|
|
47646
48614
|
function handleStatus(services, req, res) {
|
|
47647
|
-
const { getConfig, bin, store, pool, quota, warmup, catalog, auth, poolAuth, adapter, acpPool, translation, lastRun } = services;
|
|
48615
|
+
const { getConfig, bin, store, pool, quota, warmup, catalog, auth, poolAuth, adapter, acpPool, backgroundWakeup, translation, lastRun } = services;
|
|
47648
48616
|
const { version: versionCache, dormantReason } = services.status;
|
|
47649
48617
|
runRoute(res, async () => {
|
|
47650
48618
|
const cfg = getConfig();
|
|
@@ -47677,6 +48645,10 @@ function handleStatus(services, req, res) {
|
|
|
47677
48645
|
agySettings: cfg.agySettings,
|
|
47678
48646
|
transport: cfg.transport,
|
|
47679
48647
|
acpStatus: typeof acpPool?.status === "function" ? acpPool.status() : null,
|
|
48648
|
+
backgroundWakeup: cfg.backgroundWakeup,
|
|
48649
|
+
backgroundWakeupTtlMinutes: cfg.backgroundWakeupTtlMinutes,
|
|
48650
|
+
backgroundWakeupMaxPerSession: cfg.backgroundWakeupMaxPerSession,
|
|
48651
|
+
backgroundWakeState: typeof backgroundWakeup?.status === "function" ? backgroundWakeup.status() : null,
|
|
47680
48652
|
imageTool: cfg.imageTool,
|
|
47681
48653
|
syncAccountCustomizations: cfg.syncAccountCustomizations,
|
|
47682
48654
|
workspaceRoot: cfg.workspaceRoot,
|
|
@@ -48461,7 +49433,7 @@ function validateConfigValue(key, value) {
|
|
|
48461
49433
|
if (key === "warmupModels") return Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "warmupModels must be an array of model names";
|
|
48462
49434
|
if (key === "permissionMode") return typeof value === "string" && PERMISSION_MODES.has(value) ? null : "permissionMode must be skip, auto, plan, or accept-edits";
|
|
48463
49435
|
if (key === "transport") return typeof value === "string" && TRANSPORTS.has(value) ? null : "transport must be cli or acp";
|
|
48464
|
-
if (key === "sandbox" || key === "imageTool" || key === "syncAccountCustomizations") return typeof value === "boolean" ? null : `${key} must be a boolean`;
|
|
49436
|
+
if (key === "sandbox" || key === "imageTool" || key === "syncAccountCustomizations" || key === "backgroundWakeup") return typeof value === "boolean" ? null : `${key} must be a boolean`;
|
|
48465
49437
|
if (key === "agent") return typeof value === "string" ? null : "agent must be a string";
|
|
48466
49438
|
if (key === "agySettings") {
|
|
48467
49439
|
if (typeof value !== "string") return "agySettings must be a string";
|
|
@@ -48494,6 +49466,7 @@ function handleConfig(services, req, res) {
|
|
|
48494
49466
|
"transport",
|
|
48495
49467
|
"imageTool",
|
|
48496
49468
|
"syncAccountCustomizations",
|
|
49469
|
+
"backgroundWakeup",
|
|
48497
49470
|
"defaultModel",
|
|
48498
49471
|
"defaultEffort",
|
|
48499
49472
|
"askTool",
|
|
@@ -49657,6 +50630,7 @@ function apply(ctx, entryConfig = {}) {
|
|
|
49657
50630
|
lastRun: () => services.lastRun,
|
|
49658
50631
|
imageService: () => imageService,
|
|
49659
50632
|
acpStatus: () => acpPool.status(),
|
|
50633
|
+
backgroundStatus: () => services.backgroundWakeup.status(),
|
|
49660
50634
|
ecosystem: () => ecosystem,
|
|
49661
50635
|
runOnce: (req) => runAgyOnce({
|
|
49662
50636
|
cfg: getConfig,
|
|
@@ -49894,6 +50868,7 @@ function apply(ctx, entryConfig = {}) {
|
|
|
49894
50868
|
ctx.effect(() => {
|
|
49895
50869
|
return () => {
|
|
49896
50870
|
bridgeDisposed = true;
|
|
50871
|
+
services.backgroundWakeup.dispose();
|
|
49897
50872
|
services.translationWorkers?.dispose();
|
|
49898
50873
|
acpPool.dispose();
|
|
49899
50874
|
auth.dispose();
|