@0xmaxma/claude-gateway 2.0.19 → 2.0.21
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 +1 -0
- package/config.template.json +3 -2
- package/dist/agent/builtin-commands.d.ts +4 -0
- package/dist/agent/builtin-commands.d.ts.map +1 -1
- package/dist/agent/builtin-commands.js +11 -4
- package/dist/agent/builtin-commands.js.map +1 -1
- package/dist/agent/command-help.d.ts +11 -2
- package/dist/agent/command-help.d.ts.map +1 -1
- package/dist/agent/command-help.js +27 -8
- package/dist/agent/command-help.js.map +1 -1
- package/dist/agent/model-registry.d.ts +48 -0
- package/dist/agent/model-registry.d.ts.map +1 -0
- package/dist/agent/model-registry.js +144 -0
- package/dist/agent/model-registry.js.map +1 -0
- package/dist/agent/runner.d.ts +63 -41
- package/dist/agent/runner.d.ts.map +1 -1
- package/dist/agent/runner.js +304 -113
- package/dist/agent/runner.js.map +1 -1
- package/dist/agent/session-confirmations.d.ts +1 -1
- package/dist/agent/session-confirmations.d.ts.map +1 -1
- package/dist/agent/session-confirmations.js +5 -3
- package/dist/agent/session-confirmations.js.map +1 -1
- package/dist/agent/skill-learning/reviewer.d.ts.map +1 -1
- package/dist/agent/skill-learning/reviewer.js +2 -1
- package/dist/agent/skill-learning/reviewer.js.map +1 -1
- package/dist/agent/turn-stream.d.ts +2 -1
- package/dist/agent/turn-stream.d.ts.map +1 -1
- package/dist/agent/turn-stream.js.map +1 -1
- package/dist/api/gateway-router.d.ts.map +1 -1
- package/dist/api/gateway-router.js +4 -0
- package/dist/api/gateway-router.js.map +1 -1
- package/dist/api/manifest-sources.d.ts.map +1 -1
- package/dist/api/manifest-sources.js +3 -0
- package/dist/api/manifest-sources.js.map +1 -1
- package/dist/api/pstack-router.d.ts +14 -0
- package/dist/api/pstack-router.d.ts.map +1 -0
- package/dist/api/pstack-router.js +93 -0
- package/dist/api/pstack-router.js.map +1 -0
- package/dist/api/router.d.ts.map +1 -1
- package/dist/api/router.js +29 -24
- package/dist/api/router.js.map +1 -1
- package/dist/automation/computer-use.d.ts +7 -0
- package/dist/automation/computer-use.d.ts.map +1 -1
- package/dist/automation/computer-use.js +29 -7
- package/dist/automation/computer-use.js.map +1 -1
- package/dist/automation/model-choice-evaluator.d.ts +62 -3
- package/dist/automation/model-choice-evaluator.d.ts.map +1 -1
- package/dist/automation/model-choice-evaluator.js +24 -4
- package/dist/automation/model-choice-evaluator.js.map +1 -1
- package/dist/automation/vision-decider.d.ts +215 -0
- package/dist/automation/vision-decider.d.ts.map +1 -0
- package/dist/automation/vision-decider.js +673 -0
- package/dist/automation/vision-decider.js.map +1 -0
- package/dist/build-provenance.json +4 -4
- package/dist/cli/commands.generated.d.ts.map +1 -1
- package/dist/cli/commands.generated.js +36 -1
- package/dist/cli/commands.generated.js.map +1 -1
- package/dist/config/loader.d.ts.map +1 -1
- package/dist/config/loader.js +7 -0
- package/dist/config/loader.js.map +1 -1
- package/dist/config/reload-policy.js +1 -1
- package/dist/config/reload-policy.js.map +1 -1
- package/dist/config/watcher.d.ts.map +1 -1
- package/dist/config/watcher.js +2 -0
- package/dist/config/watcher.js.map +1 -1
- package/dist/orchestration/agent-tool-schemas.js +1 -1
- package/dist/orchestration/agent-tool-schemas.js.map +1 -1
- package/dist/orchestration/bridge.d.ts +6 -2
- package/dist/orchestration/bridge.d.ts.map +1 -1
- package/dist/orchestration/bridge.js +120 -5
- package/dist/orchestration/bridge.js.map +1 -1
- package/dist/orchestration/capabilities.d.ts.map +1 -1
- package/dist/orchestration/capabilities.js +10 -3
- package/dist/orchestration/capabilities.js.map +1 -1
- package/dist/orchestration/capacity.d.ts +9 -2
- package/dist/orchestration/capacity.d.ts.map +1 -1
- package/dist/orchestration/capacity.js +18 -7
- package/dist/orchestration/capacity.js.map +1 -1
- package/dist/orchestration/cli-skills.d.ts.map +1 -1
- package/dist/orchestration/cli-skills.js +4 -2
- package/dist/orchestration/cli-skills.js.map +1 -1
- package/dist/orchestration/computer-decisions.d.ts +7 -0
- package/dist/orchestration/computer-decisions.d.ts.map +1 -1
- package/dist/orchestration/computer-decisions.js +39 -0
- package/dist/orchestration/computer-decisions.js.map +1 -1
- package/dist/orchestration/config.d.ts +17 -0
- package/dist/orchestration/config.d.ts.map +1 -1
- package/dist/orchestration/config.js +21 -1
- package/dist/orchestration/config.js.map +1 -1
- package/dist/orchestration/dashboard-reader-worker.js +5 -3
- package/dist/orchestration/dashboard-reader-worker.js.map +1 -1
- package/dist/orchestration/decisions.d.ts.map +1 -1
- package/dist/orchestration/decisions.js +4 -2
- package/dist/orchestration/decisions.js.map +1 -1
- package/dist/orchestration/delivery.d.ts.map +1 -1
- package/dist/orchestration/delivery.js +1 -0
- package/dist/orchestration/delivery.js.map +1 -1
- package/dist/orchestration/gateway-tasks/computer.d.ts +10 -0
- package/dist/orchestration/gateway-tasks/computer.d.ts.map +1 -1
- package/dist/orchestration/gateway-tasks/computer.js +144 -32
- package/dist/orchestration/gateway-tasks/computer.js.map +1 -1
- package/dist/orchestration/gateway-tasks/controller.d.ts +6 -6
- package/dist/orchestration/gateway-tasks/controller.d.ts.map +1 -1
- package/dist/orchestration/gateway-tasks/controller.js +2 -2
- package/dist/orchestration/gateway-tasks/controller.js.map +1 -1
- package/dist/orchestration/input-batch.d.ts +8 -2
- package/dist/orchestration/input-batch.d.ts.map +1 -1
- package/dist/orchestration/input-batch.js +28 -8
- package/dist/orchestration/input-batch.js.map +1 -1
- package/dist/orchestration/mutation-recovery.js +1 -1
- package/dist/orchestration/mutation-recovery.js.map +1 -1
- package/dist/orchestration/notification-mailbox.d.ts.map +1 -1
- package/dist/orchestration/notification-mailbox.js +16 -2
- package/dist/orchestration/notification-mailbox.js.map +1 -1
- package/dist/orchestration/process-turn.d.ts +6 -1
- package/dist/orchestration/process-turn.d.ts.map +1 -1
- package/dist/orchestration/process-turn.js +9 -5
- package/dist/orchestration/process-turn.js.map +1 -1
- package/dist/orchestration/recovery.d.ts.map +1 -1
- package/dist/orchestration/recovery.js +21 -0
- package/dist/orchestration/recovery.js.map +1 -1
- package/dist/orchestration/response-errors.d.ts +5 -0
- package/dist/orchestration/response-errors.d.ts.map +1 -1
- package/dist/orchestration/response-errors.js +25 -0
- package/dist/orchestration/response-errors.js.map +1 -1
- package/dist/orchestration/runtime.d.ts +15 -1
- package/dist/orchestration/runtime.d.ts.map +1 -1
- package/dist/orchestration/runtime.js +155 -29
- package/dist/orchestration/runtime.js.map +1 -1
- package/dist/orchestration/speech.d.ts +3 -0
- package/dist/orchestration/speech.d.ts.map +1 -1
- package/dist/orchestration/speech.js +4 -1
- package/dist/orchestration/speech.js.map +1 -1
- package/dist/orchestration/store.d.ts +5 -0
- package/dist/orchestration/store.d.ts.map +1 -1
- package/dist/orchestration/store.js +13 -5
- package/dist/orchestration/store.js.map +1 -1
- package/dist/orchestration/subagent-tool-schemas.d.ts +12 -0
- package/dist/orchestration/subagent-tool-schemas.d.ts.map +1 -0
- package/dist/orchestration/subagent-tool-schemas.js +23 -0
- package/dist/orchestration/subagent-tool-schemas.js.map +1 -0
- package/dist/orchestration/task-controls.d.ts.map +1 -1
- package/dist/orchestration/task-controls.js +6 -3
- package/dist/orchestration/task-controls.js.map +1 -1
- package/dist/orchestration/task-questions.d.ts.map +1 -1
- package/dist/orchestration/task-questions.js +3 -1
- package/dist/orchestration/task-questions.js.map +1 -1
- package/dist/orchestration/tasks/automation-session.d.ts +17 -0
- package/dist/orchestration/tasks/automation-session.d.ts.map +1 -1
- package/dist/orchestration/tasks/automation-session.js +36 -1
- package/dist/orchestration/tasks/automation-session.js.map +1 -1
- package/dist/orchestration/tasks/driver.d.ts.map +1 -1
- package/dist/orchestration/tasks/driver.js +54 -14
- package/dist/orchestration/tasks/driver.js.map +1 -1
- package/dist/orchestration/tasks/scheduler.d.ts.map +1 -1
- package/dist/orchestration/tasks/scheduler.js +17 -3
- package/dist/orchestration/tasks/scheduler.js.map +1 -1
- package/dist/orchestration/tasks/service.d.ts +110 -34
- package/dist/orchestration/tasks/service.d.ts.map +1 -1
- package/dist/orchestration/tasks/service.js +254 -24
- package/dist/orchestration/tasks/service.js.map +1 -1
- package/dist/orchestration/tasks/task-directive.d.ts.map +1 -1
- package/dist/orchestration/tasks/task-directive.js +5 -1
- package/dist/orchestration/tasks/task-directive.js.map +1 -1
- package/dist/orchestration/telegram-tool-status.d.ts +8 -1
- package/dist/orchestration/telegram-tool-status.d.ts.map +1 -1
- package/dist/orchestration/telegram-tool-status.js +57 -6
- package/dist/orchestration/telegram-tool-status.js.map +1 -1
- package/dist/orchestration/token-ledger.d.ts +14 -0
- package/dist/orchestration/token-ledger.d.ts.map +1 -1
- package/dist/orchestration/token-ledger.js +28 -2
- package/dist/orchestration/token-ledger.js.map +1 -1
- package/dist/orchestration/token-usage.d.ts +14 -0
- package/dist/orchestration/token-usage.d.ts.map +1 -1
- package/dist/orchestration/token-usage.js +16 -2
- package/dist/orchestration/token-usage.js.map +1 -1
- package/dist/orchestration/tool-name.d.ts.map +1 -1
- package/dist/orchestration/tool-name.js +5 -1
- package/dist/orchestration/tool-name.js.map +1 -1
- package/dist/orchestration/types.d.ts +34 -0
- package/dist/orchestration/types.d.ts.map +1 -1
- package/dist/orchestration/types.js +11 -0
- package/dist/orchestration/types.js.map +1 -1
- package/dist/orchestration/worker-harness.d.ts.map +1 -1
- package/dist/orchestration/worker-harness.js +5 -2
- package/dist/orchestration/worker-harness.js.map +1 -1
- package/dist/pstack/config.d.ts +48 -0
- package/dist/pstack/config.d.ts.map +1 -0
- package/dist/pstack/config.js +147 -0
- package/dist/pstack/config.js.map +1 -0
- package/dist/pstack/menu.d.ts +71 -0
- package/dist/pstack/menu.d.ts.map +1 -0
- package/dist/pstack/menu.js +286 -0
- package/dist/pstack/menu.js.map +1 -0
- package/dist/pstack/overlay.d.ts +30 -0
- package/dist/pstack/overlay.d.ts.map +1 -0
- package/dist/pstack/overlay.js +121 -0
- package/dist/pstack/overlay.js.map +1 -0
- package/dist/pstack/plugin-info.d.ts +36 -0
- package/dist/pstack/plugin-info.d.ts.map +1 -0
- package/dist/pstack/plugin-info.js +51 -0
- package/dist/pstack/plugin-info.js.map +1 -0
- package/dist/pstack/reflect.d.ts +14 -0
- package/dist/pstack/reflect.d.ts.map +1 -0
- package/dist/pstack/reflect.js +49 -0
- package/dist/pstack/reflect.js.map +1 -0
- package/dist/pstack/setup.d.ts +17 -0
- package/dist/pstack/setup.d.ts.map +1 -0
- package/dist/pstack/setup.js +47 -0
- package/dist/pstack/setup.js.map +1 -0
- package/dist/pstack/sheet.d.ts +19 -0
- package/dist/pstack/sheet.d.ts.map +1 -0
- package/dist/pstack/sheet.js +44 -0
- package/dist/pstack/sheet.js.map +1 -0
- package/dist/pstack/templates.d.ts +14 -0
- package/dist/pstack/templates.d.ts.map +1 -0
- package/dist/pstack/templates.js +41 -0
- package/dist/pstack/templates.js.map +1 -0
- package/dist/session/codex-process.d.ts +0 -3
- package/dist/session/codex-process.d.ts.map +1 -1
- package/dist/session/codex-process.js +8 -3
- package/dist/session/codex-process.js.map +1 -1
- package/dist/session/compactor.d.ts.map +1 -1
- package/dist/session/compactor.js +2 -1
- package/dist/session/compactor.js.map +1 -1
- package/dist/session/process-diagnostics.d.ts +3 -0
- package/dist/session/process-diagnostics.d.ts.map +1 -1
- package/dist/session/process-diagnostics.js +10 -0
- package/dist/session/process-diagnostics.js.map +1 -1
- package/dist/session/process.d.ts.map +1 -1
- package/dist/session/process.js +9 -4
- package/dist/session/process.js.map +1 -1
- package/dist/session/provider-refusal.d.ts +36 -0
- package/dist/session/provider-refusal.d.ts.map +1 -0
- package/dist/session/provider-refusal.js +109 -0
- package/dist/session/provider-refusal.js.map +1 -0
- package/dist/session/runtime-profile.d.ts +13 -2
- package/dist/session/runtime-profile.d.ts.map +1 -1
- package/dist/session/runtime-profile.js +35 -2
- package/dist/session/runtime-profile.js.map +1 -1
- package/dist/session/worker-extensions.d.ts +5 -2
- package/dist/session/worker-extensions.d.ts.map +1 -1
- package/dist/session/worker-extensions.js +10 -5
- package/dist/session/worker-extensions.js.map +1 -1
- package/dist/types.d.ts +3 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/ui/dashboard-client.d.ts.map +1 -1
- package/dist/ui/dashboard-client.js +14 -4
- package/dist/ui/dashboard-client.js.map +1 -1
- package/dist/ui/dashboard-presentation.d.ts +29 -0
- package/dist/ui/dashboard-presentation.d.ts.map +1 -1
- package/dist/ui/dashboard-presentation.js +26 -1
- package/dist/ui/dashboard-presentation.js.map +1 -1
- package/dist/ui/token-report.d.ts +3 -0
- package/dist/ui/token-report.d.ts.map +1 -1
- package/dist/ui/token-report.js +1 -1
- package/dist/ui/token-report.js.map +1 -1
- package/dist/voice/errors.d.ts +6 -1
- package/dist/voice/errors.d.ts.map +1 -1
- package/dist/voice/errors.js +8 -1
- package/dist/voice/errors.js.map +1 -1
- package/dist/voice/managed-quota.d.ts +29 -3
- package/dist/voice/managed-quota.d.ts.map +1 -1
- package/dist/voice/managed-quota.js +68 -23
- package/dist/voice/managed-quota.js.map +1 -1
- package/dist/voice/notes.d.ts +27 -3
- package/dist/voice/notes.d.ts.map +1 -1
- package/dist/voice/notes.js +59 -10
- package/dist/voice/notes.js.map +1 -1
- package/mcp/lazy-tools.ts +4 -2
- package/mcp/server.ts +6 -2
- package/mcp/tools/tasks/module.ts +3 -1
- package/mcp/tools/telegram/pstack-menu.ts +22 -0
- package/mcp/tools/telegram/pure.ts +40 -0
- package/mcp/tools/telegram/receiver-server.ts +63 -6
- package/package.json +1 -1
|
@@ -1,35 +1,80 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.MANAGED_VOICE_QUOTA_EXHAUSTED = void 0;
|
|
3
|
+
exports.MANAGED_USAGE_RETRY_DELAYS_MS = exports.MANAGED_VOICE_QUOTA_EXHAUSTED = void 0;
|
|
4
|
+
exports.checkManagedVoiceCredit = checkManagedVoiceCredit;
|
|
4
5
|
exports.requireManagedVoiceCredit = requireManagedVoiceCredit;
|
|
5
6
|
const upstream_1 = require("./providers/upstream");
|
|
6
7
|
const types_1 = require("./types");
|
|
7
8
|
exports.MANAGED_VOICE_QUOTA_EXHAUSTED = 'MANAGED_VOICE_QUOTA_EXHAUSTED';
|
|
8
|
-
/**
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
/** Retry delays between wallet checks, and the time all attempts may take together. */
|
|
10
|
+
exports.MANAGED_USAGE_RETRY_DELAYS_MS = [500, 1500];
|
|
11
|
+
const MANAGED_USAGE_ATTEMPT_TIMEOUT_MS = 5000, MANAGED_USAGE_BUDGET_MS = 10000;
|
|
12
|
+
const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
|
13
|
+
/** Consult the user's wallet through the existing authenticated provider route, retrying a check
|
|
14
|
+
* that could not complete. Never cache an exhausted wallet across a reset or a credit adjustment. */
|
|
15
|
+
async function checkManagedVoiceCredit(provider, request = fetch, signal, options = {}) {
|
|
13
16
|
const { base, key } = (0, upstream_1.upstreamVoiceConnection)('elevenlabs', true);
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
+
const delays = options.retryDelaysMs ?? exports.MANAGED_USAGE_RETRY_DELAYS_MS, sleep = options.sleep ?? wait, started = Date.now();
|
|
18
|
+
let last = { code: 'MANAGED_VOICE_USAGE_UNAVAILABLE' }, attempts = 0;
|
|
19
|
+
for (let attempt = 0; attempt <= delays.length; attempt++) {
|
|
20
|
+
if (attempt) {
|
|
21
|
+
if (Date.now() - started + delays[attempt - 1] >= MANAGED_USAGE_BUDGET_MS)
|
|
22
|
+
break;
|
|
23
|
+
await sleep(delays[attempt - 1]);
|
|
24
|
+
}
|
|
25
|
+
if (signal?.aborted)
|
|
26
|
+
throw new types_1.VoiceError('PROVIDER_ABORTED');
|
|
27
|
+
attempts++;
|
|
28
|
+
const timeout = AbortSignal.timeout(Math.max(1, Math.min(MANAGED_USAGE_ATTEMPT_TIMEOUT_MS, MANAGED_USAGE_BUDGET_MS - (Date.now() - started))));
|
|
17
29
|
const effectiveSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
headers: { Authorization: `Bearer ${key}` }, signal: effectiveSignal, redirect: 'error'
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
30
|
+
let response;
|
|
31
|
+
try {
|
|
32
|
+
response = await request(new URL('../usage', base), { headers: { Authorization: `Bearer ${key}` }, signal: effectiveSignal, redirect: 'error' });
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
if (signal?.aborted)
|
|
36
|
+
throw new types_1.VoiceError('PROVIDER_ABORTED');
|
|
37
|
+
last = { code: timeout.aborted || (error instanceof Error && error.name === 'TimeoutError') ? 'MANAGED_VOICE_USAGE_TIMEOUT' : 'MANAGED_VOICE_USAGE_NETWORK' };
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
let usage;
|
|
41
|
+
try {
|
|
42
|
+
usage = await response.json();
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
usage = undefined;
|
|
46
|
+
}
|
|
47
|
+
const body = usage && typeof usage === 'object' ? usage : {};
|
|
48
|
+
// A definite "no credit" from the wallet is final; it is never retried or bypassed.
|
|
49
|
+
if (response.status === 402 || body.code === exports.MANAGED_VOICE_QUOTA_EXHAUSTED)
|
|
50
|
+
return { outcome: 'exhausted', attempts, elapsedMs: Date.now() - started };
|
|
51
|
+
if (!response.ok) {
|
|
52
|
+
last = { code: `MANAGED_VOICE_USAGE_HTTP_${response.status}`, httpStatus: response.status };
|
|
53
|
+
// Other client errors will not change on a retry.
|
|
54
|
+
if (response.status < 500 && response.status !== 408 && response.status !== 429)
|
|
55
|
+
break;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (typeof body.remaining !== 'number' || !Number.isFinite(body.remaining)) {
|
|
59
|
+
last = { code: 'MANAGED_VOICE_USAGE_INVALID_BODY' };
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
return { outcome: body.remaining <= 0 ? 'exhausted' : 'available', attempts, elapsedMs: Date.now() - started };
|
|
28
63
|
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
64
|
+
return { outcome: 'indeterminate', ...last, attempts, elapsedMs: Date.now() - started };
|
|
65
|
+
}
|
|
66
|
+
/** Stop managed voice work only on a definite exhausted wallet. A check that cannot complete
|
|
67
|
+
* (timeout, network, server error, unreadable body) lets the request through: the provider
|
|
68
|
+
* still refuses work without credit, and that refusal is reported as it already is. */
|
|
69
|
+
async function requireManagedVoiceCredit(provider, request = fetch, signal, options = {}) {
|
|
70
|
+
if (!provider.startsWith('managed:'))
|
|
71
|
+
return;
|
|
72
|
+
const check = await checkManagedVoiceCredit(provider, request, signal, options);
|
|
73
|
+
if (check.outcome !== 'available')
|
|
74
|
+
options.onDiagnostic?.({ stage: 'usage_check', ...check });
|
|
75
|
+
if (check.outcome === 'indeterminate' && !options.onDiagnostic)
|
|
76
|
+
console.warn(JSON.stringify({ ts: new Date().toISOString(), level: 'warn', event: 'Managed voice credit check incomplete; continuing', provider, ...check }));
|
|
77
|
+
if (check.outcome === 'exhausted')
|
|
33
78
|
throw new types_1.VoiceError(exports.MANAGED_VOICE_QUOTA_EXHAUSTED);
|
|
34
79
|
}
|
|
35
80
|
//# sourceMappingURL=managed-quota.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"managed-quota.js","sourceRoot":"","sources":["../../src/voice/managed-quota.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"managed-quota.js","sourceRoot":"","sources":["../../src/voice/managed-quota.ts"],"names":[],"mappings":";;;AAmBA,0DAoCC;AAKD,8DAOC;AAnED,mDAA+D;AAC/D,mCAAqC;AAExB,QAAA,6BAA6B,GAAG,+BAA+B,CAAC;AAC7E,uFAAuF;A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,MAAM,uBAAuB,CAAC,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IAChF,IAAI,KAAK,CAAC,OAAO,KAAK,WAAW;QAAE,OAAO,CAAC,YAAY,EAAE,CAAC,EAAE,KAAK,EAAE,aAAa,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC;IAC9F,IAAI,KAAK,CAAC,OAAO,KAAK,eAAe,IAAI,CAAC,OAAO,CAAC,YAAY;QAC5D,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,mDAAmD,EAAE,QAAQ,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC,CAAC;IAChK,IAAI,KAAK,CAAC,OAAO,KAAK,WAAW;QAAE,MAAM,IAAI,kBAAU,CAAC,qCAA6B,CAAC,CAAC;AACzF,CAAC"}
|
package/dist/voice/notes.d.ts
CHANGED
|
@@ -1,9 +1,33 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import { ManagedCreditCheck } from './managed-quota';
|
|
2
|
+
/** Delays before the 2nd and 3rd transcription attempt, and the time all attempts may take. */
|
|
3
|
+
export declare const TRANSCRIPTION_RETRY_DELAYS_MS: number[];
|
|
4
|
+
export type VoiceNoteDiagnostic = (ManagedCreditCheck & {
|
|
5
|
+
stage: 'usage_check';
|
|
6
|
+
}) | {
|
|
7
|
+
stage: 'transcription';
|
|
8
|
+
outcome: 'retry' | 'failed';
|
|
9
|
+
code: string;
|
|
10
|
+
attempt: number;
|
|
11
|
+
elapsedMs: number;
|
|
12
|
+
httpStatus?: number;
|
|
13
|
+
};
|
|
14
|
+
export interface VoiceNoteOptions {
|
|
3
15
|
provider: string;
|
|
4
16
|
model: string;
|
|
5
17
|
language?: string;
|
|
6
|
-
|
|
18
|
+
retryDelaysMs?: number[];
|
|
19
|
+
sleep?: (ms: number) => Promise<void>;
|
|
20
|
+
onDiagnostic?: (event: VoiceNoteDiagnostic) => void;
|
|
21
|
+
}
|
|
22
|
+
/** A transcription failure worth another attempt: no answer in time, no connection, a server
|
|
23
|
+
* error or a plain rate limit. Auth, payment, quota, format and other client errors are final. */
|
|
24
|
+
export declare function retryableTranscriptionError(code: string): boolean;
|
|
25
|
+
/** Uploaded voice notes use the file API, not a realtime PCM socket. */
|
|
26
|
+
export declare function transcribeVoiceNote(path: string, options: VoiceNoteOptions, request?: typeof fetch): Promise<string>;
|
|
27
|
+
/** A stored voice-note failure that a retry from the kept audio can fix: the provider or the
|
|
28
|
+
* credit check could not finish, or the run was interrupted. Missing credit, auth, format and
|
|
29
|
+
* empty-speech failures are final. */
|
|
30
|
+
export declare function retryableVoiceNoteFailure(code: string): boolean;
|
|
7
31
|
/** Keep provider diagnostics consistent across chat channels and browser voice. */
|
|
8
32
|
export declare function voiceNoteFailureMessage(code: string): string;
|
|
9
33
|
//# sourceMappingURL=notes.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"notes.d.ts","sourceRoot":"","sources":["../../src/voice/notes.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"notes.d.ts","sourceRoot":"","sources":["../../src/voice/notes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAA6B,MAAM,iBAAiB,CAAC;AAYhF,+FAA+F;AAC/F,eAAO,MAAM,6BAA6B,UAAe,CAAC;AAE1D,MAAM,MAAM,mBAAmB,GAC3B,CAAC,kBAAkB,GAAG;IAAE,KAAK,EAAE,aAAa,CAAA;CAAE,CAAC,GAC/C;IAAE,KAAK,EAAE,eAAe,CAAC;IAAC,OAAO,EAAE,OAAO,GAAG,QAAQ,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AACnI,MAAM,WAAW,gBAAgB;IAAG,QAAQ,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAAC,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAAC,YAAY,CAAC,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI,CAAA;CAAE;AAE9M;kGACkG;AAClG,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAOjE;AAED,wEAAwE;AACxE,wBAAsB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,EAAE,OAAO,GAAE,OAAO,KAAa,GAAG,OAAO,CAAC,MAAM,CAAC,CAkBjI;AA8BD;;sCAEsC;AACtC,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAI/D;AAED,mFAAmF;AACnF,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAW5D"}
|
package/dist/voice/notes.js
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TRANSCRIPTION_RETRY_DELAYS_MS = void 0;
|
|
4
|
+
exports.retryableTranscriptionError = retryableTranscriptionError;
|
|
3
5
|
exports.transcribeVoiceNote = transcribeVoiceNote;
|
|
6
|
+
exports.retryableVoiceNoteFailure = retryableVoiceNoteFailure;
|
|
4
7
|
exports.voiceNoteFailureMessage = voiceNoteFailureMessage;
|
|
5
8
|
const managed_quota_1 = require("./managed-quota");
|
|
9
|
+
const types_1 = require("./types");
|
|
6
10
|
const errors_1 = require("./errors");
|
|
7
11
|
const model_ref_1 = require("./providers/model-ref");
|
|
8
12
|
const openrouter_1 = require("./providers/openrouter");
|
|
@@ -11,29 +15,65 @@ const paxalabs_stt_1 = require("./providers/paxalabs-stt");
|
|
|
11
15
|
const upstream_1 = require("./providers/upstream");
|
|
12
16
|
const promises_1 = require("fs/promises");
|
|
13
17
|
const path_1 = require("path");
|
|
14
|
-
const
|
|
18
|
+
const types_2 = require("../orchestration/types");
|
|
19
|
+
/** Delays before the 2nd and 3rd transcription attempt, and the time all attempts may take. */
|
|
20
|
+
exports.TRANSCRIPTION_RETRY_DELAYS_MS = [1000, 3000];
|
|
21
|
+
const TRANSCRIPTION_ATTEMPT_TIMEOUT_MS = 60000, TRANSCRIPTION_BUDGET_MS = 120000;
|
|
22
|
+
/** A transcription failure worth another attempt: no answer in time, no connection, a server
|
|
23
|
+
* error or a plain rate limit. Auth, payment, quota, format and other client errors are final. */
|
|
24
|
+
function retryableTranscriptionError(code) {
|
|
25
|
+
if (code === 'PROVIDER_TIMEOUT' || code === 'PROVIDER_CONNECTION_FAILED')
|
|
26
|
+
return true;
|
|
27
|
+
const match = /_HTTP_(\d{3})(?:_REASON_([A-Z_]+))?$/.exec(code);
|
|
28
|
+
if (!match)
|
|
29
|
+
return false;
|
|
30
|
+
const status = Number(match[1]), reason = match[2];
|
|
31
|
+
if (status === 429)
|
|
32
|
+
return !reason || reason === 'RATE_LIMIT';
|
|
33
|
+
return (status >= 500 || status === 408) && (!reason || reason === 'UNAVAILABLE' || reason === 'TIMEOUT');
|
|
34
|
+
}
|
|
15
35
|
/** Uploaded voice notes use the file API, not a realtime PCM socket. */
|
|
16
36
|
async function transcribeVoiceNote(path, options, request = fetch) {
|
|
17
37
|
options = { ...options, provider: (0, model_ref_1.canonicalVoiceProvider)(options.provider), model: (0, model_ref_1.nativeVoiceModel)(options.provider, options.model) };
|
|
18
|
-
|
|
38
|
+
const sleep = options.sleep ?? ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
|
|
39
|
+
await (0, managed_quota_1.requireManagedVoiceCredit)(options.provider, request, undefined, { sleep, ...(options.onDiagnostic ? { onDiagnostic: options.onDiagnostic } : {}) });
|
|
40
|
+
const delays = options.retryDelaysMs ?? exports.TRANSCRIPTION_RETRY_DELAYS_MS, started = Date.now();
|
|
41
|
+
for (let attempt = 1;; attempt++) {
|
|
42
|
+
const remaining = TRANSCRIPTION_BUDGET_MS - (Date.now() - started);
|
|
43
|
+
try {
|
|
44
|
+
return await transcribeOnce(path, options, request, AbortSignal.timeout(Math.max(1, Math.min(TRANSCRIPTION_ATTEMPT_TIMEOUT_MS, remaining))));
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
const code = error instanceof types_1.VoiceError || error instanceof types_2.OrchestrationError ? error.code : '';
|
|
48
|
+
const delay = delays[attempt - 1];
|
|
49
|
+
const retry = retryableTranscriptionError(code) && delay !== undefined && Date.now() - started + delay < TRANSCRIPTION_BUDGET_MS;
|
|
50
|
+
const httpStatus = Number(/_HTTP_(\d{3})/.exec(code)?.[1]) || undefined;
|
|
51
|
+
options.onDiagnostic?.({ stage: 'transcription', outcome: retry ? 'retry' : 'failed', code: code || 'VOICE_NOTE_STT_FAILED', attempt, elapsedMs: Date.now() - started, ...(httpStatus ? { httpStatus } : {}) });
|
|
52
|
+
if (!retry)
|
|
53
|
+
throw error;
|
|
54
|
+
await sleep(delay);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
async function transcribeOnce(path, options, request, signal) {
|
|
19
59
|
if (['paxalabs', 'upstream:paxalabs', 'managed:paxalabs', 'gemini', 'upstream:gemini', 'openrouter', 'upstream:openrouter'].includes(options.provider)) {
|
|
20
60
|
const info = await (0, promises_1.stat)(path);
|
|
21
61
|
if (!info.isFile() || !info.size || info.size > 25 * 1024 * 1024)
|
|
22
|
-
throw new
|
|
23
|
-
const text = await (options.provider.includes('gemini') ? gemini_1.transcribeGemini : options.provider.includes('openrouter') ? openrouter_1.transcribeOpenRouter : paxalabs_stt_1.transcribePaxa)(await (0, promises_1.readFile)(path), { ...options, signal
|
|
62
|
+
throw new types_2.OrchestrationError('VOICE_NOTE_SIZE_LIMIT');
|
|
63
|
+
const text = await (options.provider.includes('gemini') ? gemini_1.transcribeGemini : options.provider.includes('openrouter') ? openrouter_1.transcribeOpenRouter : paxalabs_stt_1.transcribePaxa)(await (0, promises_1.readFile)(path), { ...options, signal }, request);
|
|
24
64
|
if (!text)
|
|
25
|
-
throw new
|
|
65
|
+
throw new types_2.OrchestrationError('VOICE_NOTE_NO_TRANSCRIPT');
|
|
26
66
|
return text;
|
|
27
67
|
}
|
|
28
68
|
if (!['elevenlabs', 'upstream:elevenlabs', 'managed:elevenlabs'].includes(options.provider))
|
|
29
|
-
throw new
|
|
69
|
+
throw new types_2.OrchestrationError('VOICE_NOTE_PROVIDER_UNSUPPORTED');
|
|
30
70
|
const upstream = options.provider === 'managed:elevenlabs' ? (0, upstream_1.upstreamVoiceConnection)('elevenlabs', true) : options.provider === 'upstream:elevenlabs' ? (0, upstream_1.upstreamVoiceConnection)() : undefined;
|
|
31
71
|
const key = upstream?.key || process.env.ELEVENLABS_API_KEY;
|
|
32
72
|
if (!key)
|
|
33
|
-
throw new
|
|
73
|
+
throw new types_2.OrchestrationError('STT_CREDENTIALS_MISSING');
|
|
34
74
|
const info = await (0, promises_1.stat)(path);
|
|
35
75
|
if (!info.isFile() || !info.size || info.size > 20 * 1024 * 1024)
|
|
36
|
-
throw new
|
|
76
|
+
throw new types_2.OrchestrationError('VOICE_NOTE_SIZE_LIMIT');
|
|
37
77
|
const data = new FormData();
|
|
38
78
|
data.set('model_id', options.model);
|
|
39
79
|
data.set('file', new Blob([new Uint8Array(await (0, promises_1.readFile)(path))]), (0, path_1.basename)(path));
|
|
@@ -42,15 +82,24 @@ async function transcribeVoiceNote(path, options, request = fetch) {
|
|
|
42
82
|
if (options.language)
|
|
43
83
|
data.set('language_code', options.language);
|
|
44
84
|
const response = await (0, errors_1.voiceProviderRequest)(upstream ? new URL('speech-to-text', upstream.base).toString() : 'https://api.elevenlabs.io/v1/speech-to-text', {
|
|
45
|
-
method: 'POST', headers: upstream ? { Authorization: `Bearer ${key}` } : { 'xi-api-key': key }, body: data, signal
|
|
85
|
+
method: 'POST', headers: upstream ? { Authorization: `Bearer ${key}` } : { 'xi-api-key': key }, body: data, signal, redirect: 'error',
|
|
46
86
|
}, request);
|
|
47
87
|
if (!response.ok)
|
|
48
88
|
throw await (0, errors_1.providerHttpError)('STT', response);
|
|
49
89
|
const result = await response.json();
|
|
50
90
|
if (typeof result.text !== 'string' || !result.text.trim() || Buffer.byteLength(result.text) > 60000)
|
|
51
|
-
throw new
|
|
91
|
+
throw new types_2.OrchestrationError('VOICE_NOTE_NO_TRANSCRIPT');
|
|
52
92
|
return result.text.trim();
|
|
53
93
|
}
|
|
94
|
+
/** A stored voice-note failure that a retry from the kept audio can fix: the provider or the
|
|
95
|
+
* credit check could not finish, or the run was interrupted. Missing credit, auth, format and
|
|
96
|
+
* empty-speech failures are final. */
|
|
97
|
+
function retryableVoiceNoteFailure(code) {
|
|
98
|
+
if (code === 'VOICE_NOTE_INTERRUPTED' || code === 'VOICE_NOTE_STT_FAILED')
|
|
99
|
+
return true;
|
|
100
|
+
const diagnostic = (0, errors_1.describeVoiceError)(code);
|
|
101
|
+
return diagnostic.retryable || diagnostic.category === 'quota_or_rate_limit';
|
|
102
|
+
}
|
|
54
103
|
/** Keep provider diagnostics consistent across chat channels and browser voice. */
|
|
55
104
|
function voiceNoteFailureMessage(code) {
|
|
56
105
|
const local = {
|
package/dist/voice/notes.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"notes.js","sourceRoot":"","sources":["../../src/voice/notes.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"notes.js","sourceRoot":"","sources":["../../src/voice/notes.ts"],"names":[],"mappings":";;;AAsBA,kEAOC;AAGD,kDAkBC;AAiCD,8DAIC;AAGD,0DAWC;AArGD,mDAAgF;AAChF,mCAAqC;AACrC,qCAAuF;AACvF,qDAAiF;AACjF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C,0BAA0B,CAAC,CAAC;IAC/J,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;AAC5B,CAAC;AAED;;sCAEsC;AACtC,SAAgB,yBAAyB,CAAC,IAAY;IACpD,IAAI,IAAI,KAAK,wBAAwB,IAAI,IAAI,KAAK,uBAAuB;QAAE,OAAO,IAAI,CAAC;IACvF,MAAM,UAAU,GAAG,IAAA,2BAAkB,EAAC,IAAI,CAAC,CAAC;IAC5C,OAAO,UAAU,CAAC,SAAS,IAAI,UAAU,CAAC,QAAQ,KAAK,qBAAqB,CAAC;AAC/E,CAAC;AAED,mFAAmF;AACnF,SAAgB,uBAAuB,CAAC,IAAY;IAClD,MAAM,KAAK,GAA2B;QACpC,wBAAwB,EAAE,wFAAwF;QAClH,qBAAqB,EAAE,mGAAmG;QAC1H,oBAAoB,EAAE,yDAAyD;QAC/E,6BAA6B,EAAE,8EAA8E;QAC7G,+BAA+B,EAAE,2GAA2G;QAC5I,sBAAsB,EAAE,kFAAkF;KAC3G,CAAC;IACF,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC;QAAE,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC;IAC1E,OAAO,wCAAwC,IAAA,2BAAkB,EAAC,IAAI,CAAC,CAAC,OAAO,EAAE,CAAC;AACpF,CAAC"}
|
package/mcp/lazy-tools.ts
CHANGED
|
@@ -33,9 +33,11 @@ export function createLazyToolCatalog(tools: readonly McpToolDefinition[], exclu
|
|
|
33
33
|
tools: matches.slice(offset, offset + limit).map(tool => schemas ? tool : { name: tool.name, description: tool.description }) });
|
|
34
34
|
},
|
|
35
35
|
async call(args: Record<string, unknown>, dispatch: (name: string, input: Record<string, unknown>) => Promise<McpToolResult>): Promise<McpToolResult> {
|
|
36
|
-
|
|
36
|
+
// A model knows these tools by their MCP names (`mcp__gateway__x`); the catalog holds the bare `x`.
|
|
37
|
+
const name = typeof args.name === 'string' ? args.name.replace(/^mcp__gateway__/, '') : undefined;
|
|
38
|
+
if (!name || !names.has(name)) return fail('Unknown or unauthorized gateway tool');
|
|
37
39
|
if (!args.arguments || typeof args.arguments !== 'object' || Array.isArray(args.arguments)) return fail('Tool arguments must be an object');
|
|
38
|
-
return dispatch(
|
|
40
|
+
return dispatch(name, args.arguments as Record<string, unknown>);
|
|
39
41
|
},
|
|
40
42
|
};
|
|
41
43
|
}
|
package/mcp/server.ts
CHANGED
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
CallToolRequestSchema,
|
|
14
14
|
} from '@modelcontextprotocol/sdk/types.js';
|
|
15
15
|
import { gatewayModules } from './modules';
|
|
16
|
-
import { AGENT_TASK_TOOLS, WORKER_REPORT_TOOLS, callTaskBridge } from './tools/tasks/module';
|
|
16
|
+
import { AGENT_TASK_TOOLS, SUBAGENT_TOOLS, WORKER_REPORT_TOOLS, callTaskBridge, readonlyDenied } from './tools/tasks/module';
|
|
17
17
|
import { createLazyToolCatalog, LAZY_TOOL_DEFINITIONS } from './lazy-tools';
|
|
18
18
|
import { buildChannelInstructions } from './instructions';
|
|
19
19
|
import type { ChannelModule, ToolModule, McpToolDefinition } from './types';
|
|
@@ -61,8 +61,12 @@ for (const mod of modules) {
|
|
|
61
61
|
// mid-session and invalidated the whole cache — the same defect ee800a7 fixed for the response
|
|
62
62
|
// schema. The turn's INTAKE_OVERLAY prompt text, below the cache breakpoint, is what asks for
|
|
63
63
|
// the tool; the bridge refuses the call outright when the feature is not active.
|
|
64
|
-
const taskTools = ORCHESTRATION_ROLE === 'agent' ? AGENT_TASK_TOOLS.filter(tool => (tool.name !== 'jev_evaluate' || process.env.GATEWAY_JEV_ENABLED === 'true')).filter(tool => tool.name !== 'capabilities_list' || process.env.GATEWAY_CAPABILITY_CATALOG === 'true') : ORCHESTRATION_ROLE === 'worker' ? WORKER_REPORT_TOOLS.filter(tool => (tool.name !== 'jev_evaluate' || process.env.GATEWAY_JEV_ENABLED === 'true')).filter(tool => tool.name !== 'task_memory_append' || process.env.GATEWAY_ORCHESTRATION_WRITE_MEMORY === 'true') : [];
|
|
64
|
+
const taskTools = ORCHESTRATION_ROLE === 'agent' ? AGENT_TASK_TOOLS.filter(tool => (tool.name !== 'jev_evaluate' || process.env.GATEWAY_JEV_ENABLED === 'true')).filter(tool => tool.name !== 'capabilities_list' || process.env.GATEWAY_CAPABILITY_CATALOG === 'true') : ORCHESTRATION_ROLE === 'worker' ? WORKER_REPORT_TOOLS.filter(tool => (tool.name !== 'jev_evaluate' || process.env.GATEWAY_JEV_ENABLED === 'true')).filter(tool => tool.name !== 'task_memory_append' || process.env.GATEWAY_ORCHESTRATION_WRITE_MEMORY === 'true').concat(process.env.GATEWAY_SUBAGENTS === 'true' ? SUBAGENT_TOOLS : []) : [];
|
|
65
65
|
if (ORCHESTRATION_ROLE && process.env.GATEWAY_ORCHESTRATION_TICKET_FILE) visibleTools.push(...taskTools);
|
|
66
|
+
// A read-only subagent sees only tools that change nothing; the bridge refuses the rest.
|
|
67
|
+
if (ORCHESTRATION_ROLE === 'worker' && process.env.GATEWAY_READONLY_TASK === 'true') {
|
|
68
|
+
for (let i = visibleTools.length - 1; i >= 0; i--) if (readonlyDenied(visibleTools[i].name)) { toolMap.delete(visibleTools[i].name); visibleTools.splice(i, 1); }
|
|
69
|
+
}
|
|
66
70
|
|
|
67
71
|
// Preserve the full policy-filtered inventory internally; only schema exposure is lazy.
|
|
68
72
|
const lazyEnabled = ORCHESTRATION_ROLE === 'worker' && process.env.GATEWAY_LAZY_TOOLS === 'true';
|
|
@@ -7,6 +7,7 @@ import type { McpToolDefinition, McpToolResult } from '../../types';
|
|
|
7
7
|
const schema = (properties: Record<string, unknown>, required: string[]) => ({ type: 'object', properties, required, additionalProperties: false });
|
|
8
8
|
const text = { type: 'string' };
|
|
9
9
|
export { AGENT_TASK_TOOLS } from '../../../dist/orchestration/agent-tool-schemas.js';
|
|
10
|
+
export { SUBAGENT_TOOLS, readonlyDenied } from '../../../dist/orchestration/subagent-tool-schemas.js';
|
|
10
11
|
export const WORKER_REPORT_TOOLS: McpToolDefinition[] = [
|
|
11
12
|
JEV_TOOL,
|
|
12
13
|
{ name: 'task_memory_append', description: 'Append an explicitly requested memory note for a channel task. API tasks cannot write memory. Files are restricted to MEMORY.md, USER.md, or memory/<name>.md. Retains existing content and deduplicates retries.', inputSchema: schema({ note: text, path: text }, ['note']) },
|
|
@@ -15,7 +16,8 @@ export const WORKER_REPORT_TOOLS: McpToolDefinition[] = [
|
|
|
15
16
|
{ name: 'task_request_input', description: 'Ask the user for information required by your task, then end this turn immediately.', inputSchema: schema({ question: text }, ['question']) },
|
|
16
17
|
];
|
|
17
18
|
|
|
18
|
-
|
|
19
|
+
// subagent_wait (and a foreground subagent_spawn) answers when the subagent finishes, as native `Agent` does.
|
|
20
|
+
const LONG_RUNNING_TOOLS = new Set(['narrate', 'subagent_wait', 'subagent_spawn']);
|
|
19
21
|
export const LONG_RUNNING_MAX_MS = 2 * 60 * 60 * 1000;
|
|
20
22
|
export async function callTaskBridge(tool: string, args: Record<string, unknown>, requestId: string, signal: AbortSignal): Promise<McpToolResult> {
|
|
21
23
|
// Rotated by the gateway at each decision/attempt boundary. A loaded token is
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { InlineKeyboard } from 'grammy'
|
|
2
|
+
|
|
3
|
+
/** One /pstack-setup screen as the gateway renders it (`telegram_pstack`). `done`: a final result, shown without buttons. */
|
|
4
|
+
export type PstackMenu = { text: string; keyboard: Array<Array<{ text: string; data: string }>>; closed?: boolean; done?: boolean; toast?: string }
|
|
5
|
+
|
|
6
|
+
/** Telegram caps callback_data at 64 UTF-8 bytes and text at 4096 characters. */
|
|
7
|
+
const MAX_DATA_BYTES = 64
|
|
8
|
+
const MAX_TEXT = 4096
|
|
9
|
+
|
|
10
|
+
/** Validate the gateway's screen and build its keyboard; a malformed button is dropped, not sent. */
|
|
11
|
+
export function pstackMenuMarkup(value: unknown): { text: string; reply_markup: InlineKeyboard; closed: boolean; done: boolean; toast?: string } {
|
|
12
|
+
const menu = value as Partial<PstackMenu>
|
|
13
|
+
if (typeof menu?.text !== 'string' || !Array.isArray(menu.keyboard)) throw Error('INVALID_PSTACK_MENU')
|
|
14
|
+
const rows = menu.keyboard.filter(Array.isArray).map(row => row
|
|
15
|
+
.filter(button => typeof button?.text === 'string' && typeof button?.data === 'string' && button.data.startsWith('ps:') && Buffer.byteLength(button.data, 'utf8') <= MAX_DATA_BYTES)
|
|
16
|
+
.map(button => InlineKeyboard.text(button.text.slice(0, 64), button.data))).filter(row => row.length)
|
|
17
|
+
const keyboard = new InlineKeyboard(rows)
|
|
18
|
+
return { text: menu.text.slice(0, MAX_TEXT), reply_markup: keyboard, closed: menu.closed === true, done: menu.done === true, ...(typeof menu.toast === 'string' ? { toast: menu.toast.slice(0, 180) } : {}) }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** `/pstack-setup` or `/pstack_setup` with nothing after it opens the menu; with arguments it is the text command. */
|
|
22
|
+
export const PSTACK_MENU_COMMAND = /^\/pstack[-_]setup(?:@\w+)?\s*$/i
|
|
@@ -339,10 +339,50 @@ export function normalizeTelegramLineBreaks(text: string): string {
|
|
|
339
339
|
return text.replace(/(?:<|<)br\s*\/?(?:>|>)/gi, '\n')
|
|
340
340
|
}
|
|
341
341
|
|
|
342
|
+
/** Commands the receiver answers itself, in a direct message only (and `cli` where the terminal viewer is on). */
|
|
343
|
+
const DM_ONLY_COMMANDS = ['start', 'help', 'status', 'model', 'models', 'clear', 'compact', 'restart', 'session', 'sessions', 'tasks', 'voice', 'voices']
|
|
344
|
+
/** Commands forwarded to the gateway, which answers them in a group as well. */
|
|
345
|
+
const GROUP_COMMANDS = ['stop', 'new', 'rename', 'pstack_setup', 'pstack-setup']
|
|
346
|
+
|
|
347
|
+
/** The leading `/name` or `/name@<this bot>` of a message, lowercased; undefined when there is none or it names another bot. */
|
|
348
|
+
export function leadingCommand(text: string, botUsername: string): string | undefined {
|
|
349
|
+
const match = /^\/([a-z0-9_-]+)(?:@(\w+))?(?=\s|$)/i.exec(text.trim())
|
|
350
|
+
if (!match || (match[2] && match[2].toLowerCase() !== botUsername.toLowerCase())) return undefined
|
|
351
|
+
return match[1]!.toLowerCase()
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** A gateway command typed in a group is addressed to this bot, the same as a mention. */
|
|
355
|
+
export function isGroupCommand(text: string, botUsername: string): boolean {
|
|
356
|
+
return GROUP_COMMANDS.includes(leadingCommand(text, botUsername) ?? '')
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** `/name@<this bot> …` → `/name …`, so the gateway matches the command it was sent. */
|
|
360
|
+
export function stripCommandTarget(text: string, botUsername: string): string {
|
|
361
|
+
const match = /^(\s*\/[a-z0-9_-]+)@(\w+)(?=\s|$)/i.exec(text)
|
|
362
|
+
return match && botUsername && match[2]!.toLowerCase() === botUsername.toLowerCase() ? match[1] + text.slice(match[0].length) : text
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* The reply to a direct-message-only command typed in a group, or undefined.
|
|
367
|
+
* Only a group whose messages the gate delivers gets one; others stay silent,
|
|
368
|
+
* as the gate keeps them. The gate decides on a copy with pairing off and the
|
|
369
|
+
* mention rule waived, so no pairing code is minted and nothing is saved.
|
|
370
|
+
*/
|
|
371
|
+
export function groupCommandReply(access: Access, input: { chatType?: string; chatId: string; fromId: string; text: string; botUsername: string; cliEnabled?: boolean }): string | undefined {
|
|
372
|
+
if (input.chatType !== 'group' && input.chatType !== 'supergroup') return undefined
|
|
373
|
+
const name = leadingCommand(input.text, input.botUsername)
|
|
374
|
+
if (!name || !(DM_ONLY_COMMANDS.includes(name) || (name === 'cli' && input.cliEnabled))) return undefined
|
|
375
|
+
const copy: Access = { ...access, pairing: false, requireMention: false, pending: { ...access.pending } }
|
|
376
|
+
const verdict = gateLogic({ fromId: input.fromId, chatType: input.chatType, chatId: input.chatId, botUsername: input.botUsername, messageText: input.text },
|
|
377
|
+
() => copy, () => {}, () => { throw Error('NO_PAIRING_IN_GROUP_COMMAND_REPLY') })
|
|
378
|
+
return verdict.action === 'deliver' ? `/${name} is only available in a direct message with the bot.` : undefined
|
|
379
|
+
}
|
|
380
|
+
|
|
342
381
|
export function isMentionedPure(input: GateInput, extraPatterns?: string[]): boolean {
|
|
343
382
|
const entities = input.messageEntities ?? input.captionEntities ?? []
|
|
344
383
|
const text = input.messageText ?? ''
|
|
345
384
|
const botUsername = input.botUsername ?? ''
|
|
385
|
+
if (isGroupCommand(text, botUsername)) return true
|
|
346
386
|
|
|
347
387
|
for (const e of entities) {
|
|
348
388
|
if (e.type === 'mention') {
|
|
@@ -29,6 +29,7 @@ import type { ReactionTypeEmoji } from 'grammy/types'
|
|
|
29
29
|
import { randomBytes } from 'crypto'
|
|
30
30
|
import { confirmSelection, voiceModeConfirmation } from './selection-confirmation'
|
|
31
31
|
import { LiveTaskBrowser, type TaskBrowserMessage } from './task-browser'
|
|
32
|
+
import { PSTACK_MENU_COMMAND, pstackMenuMarkup } from './pstack-menu'
|
|
32
33
|
import { ReceiverSpool } from '../receiver-spool'
|
|
33
34
|
const orchestrationSpool = process.env.GATEWAY_ORCHESTRATION_INGRESS_DIR && process.env.CLAUDE_CHANNEL_CALLBACK
|
|
34
35
|
? new ReceiverSpool(process.env.GATEWAY_ORCHESTRATION_INGRESS_DIR, process.env.CLAUDE_CHANNEL_CALLBACK, fetch, Math.max(250,Math.min(10000,Number(process.env.GATEWAY_MEDIA_GROUP_WAIT_MS)||2000))) : undefined
|
|
@@ -49,7 +50,7 @@ import { formatTurnIncident, type TurnIncident } from '../../../dist/agent/turn-
|
|
|
49
50
|
import { createIncidentStore } from '../../../dist/agent/incident-store.js'
|
|
50
51
|
import type { RecoveryOutcome } from '../../../dist/agent/incident.js'
|
|
51
52
|
import { initDedupDir, isDuplicate as _isDuplicate, pruneDedup as _pruneDedup } from './dedup'
|
|
52
|
-
import { normalizeTelegramLineBreaks, resolveTelegramReplyFormat, migrateAccess, telegramDisplayName } from './pure'
|
|
53
|
+
import { normalizeTelegramLineBreaks, resolveTelegramReplyFormat, migrateAccess, telegramDisplayName, groupCommandReply, isGroupCommand, stripCommandTarget } from './pure'
|
|
53
54
|
import { MAX_ATTACHMENT_BYTES } from '../shared/limits'
|
|
54
55
|
|
|
55
56
|
// Standalone fallback: default state dir to ~/.claude/channels/telegram
|
|
@@ -526,6 +527,7 @@ function countPending(access: Access, kind: 'dm' | 'group'): number {
|
|
|
526
527
|
function isMentioned(ctx: Context, extraPatterns?: string[]): boolean {
|
|
527
528
|
const entities = ctx.message?.entities ?? ctx.message?.caption_entities ?? []
|
|
528
529
|
const text = ctx.message?.text ?? ctx.message?.caption ?? ''
|
|
530
|
+
if (isGroupCommand(text, botUsername)) return true
|
|
529
531
|
for (const e of entities) {
|
|
530
532
|
if (e.type === 'mention') {
|
|
531
533
|
const mentioned = text.slice(e.offset, e.offset + e.length)
|
|
@@ -885,6 +887,7 @@ const BOT_COMMANDS = [
|
|
|
885
887
|
{ command: 'restart', description: 'Graceful restart session' },
|
|
886
888
|
{ command: 'model', description: 'Show current AI model' },
|
|
887
889
|
{ command: 'models', description: 'Switch AI model' },
|
|
890
|
+
{ command: 'pstack_setup', description: 'Set up pstack for this agent' },
|
|
888
891
|
...(INTERACTIVE_CLI_ENABLED ? [{ command: 'cli', description: 'Open the live terminal viewer' }] : []),
|
|
889
892
|
{ command: 'start', description: 'Welcome and setup guide' },
|
|
890
893
|
{ command: 'status', description: 'Check your pairing status' },
|
|
@@ -922,7 +925,8 @@ const AVAILABLE_MODELS = [
|
|
|
922
925
|
{ id: 'claude-sonnet-5-5', label: 'Sonnet 5.5', alias: 'sonnet' },
|
|
923
926
|
{ id: 'claude-sonnet-5', label: 'Sonnet 5', alias: 'sonnet5' },
|
|
924
927
|
{ id: 'claude-sonnet-4-6', label: 'Sonnet 4.6', alias: 'sonnet46' },
|
|
925
|
-
{ id: 'claude-haiku-
|
|
928
|
+
{ id: 'claude-haiku-5-5', label: 'Haiku 5.5', alias: 'haiku' },
|
|
929
|
+
{ id: 'claude-haiku-4-5-20251001', label: 'Haiku 4.5', alias: 'haiku45' },
|
|
926
930
|
{ id: 'gpt-6-sol[1m]', label: 'GPT 6 Sol', alias: 'gpt6sol' },
|
|
927
931
|
{ id: 'gpt-6-astra[1m]', label: 'GPT 6 Astra', alias: 'gpt6astra' },
|
|
928
932
|
{ id: 'gpt-6-luna[1m]', label: 'GPT 6 Luna', alias: 'gpt6luna' },
|
|
@@ -993,6 +997,7 @@ async function handleInbound(
|
|
|
993
997
|
const access = result.access
|
|
994
998
|
const from = ctx.from!
|
|
995
999
|
const chat_id = String(ctx.chat!.id)
|
|
1000
|
+
text = stripCommandTarget(text, botUsername)
|
|
996
1001
|
const msgId = ctx.message?.message_id
|
|
997
1002
|
|
|
998
1003
|
// Permission-reply intercept: if this looks like "yes xxxxx" for a
|
|
@@ -1144,10 +1149,16 @@ async function handleInbound(
|
|
|
1144
1149
|
|
|
1145
1150
|
if (!SEND_ONLY) {
|
|
1146
1151
|
|
|
1147
|
-
// Commands are DM-only.
|
|
1148
|
-
// /status to other
|
|
1149
|
-
//
|
|
1150
|
-
//
|
|
1152
|
+
// Commands are DM-only. Answering them in a group would leak pairing codes via
|
|
1153
|
+
// /status to other members and act for the whole agent from a shared chat, so
|
|
1154
|
+
// an allowed group gets a pointer to the direct message instead; a group the
|
|
1155
|
+
// gate does not allow stays silent, so its members learn nothing. /stop, /new,
|
|
1156
|
+
// /rename and /pstack_setup are forwarded and answered by the gateway there.
|
|
1157
|
+
bot.on('message:text', async (ctx, next) => {
|
|
1158
|
+
const reply = groupCommandReply(loadAccess(), { chatType: ctx.chat.type, chatId: String(ctx.chat.id), fromId: String(ctx.from.id), text: ctx.message.text, botUsername, cliEnabled: INTERACTIVE_CLI_ENABLED })
|
|
1159
|
+
if (reply === undefined) return next()
|
|
1160
|
+
await ctx.reply(reply, { reply_parameters: { message_id: ctx.message.message_id } }).catch(() => {})
|
|
1161
|
+
})
|
|
1151
1162
|
|
|
1152
1163
|
bot.command('start', async ctx => {
|
|
1153
1164
|
if (ctx.chat?.type !== 'private') return
|
|
@@ -1447,6 +1458,24 @@ bot.command('tasks',async ctx=>{
|
|
|
1447
1458
|
catch{await ctx.reply('Could not load tasks. Please try /tasks again.')}
|
|
1448
1459
|
})
|
|
1449
1460
|
|
|
1461
|
+
// /pstack-setup (Telegram also takes /pstack_setup: command names cannot contain '-').
|
|
1462
|
+
// Bare, it opens the button menu the gateway renders; with arguments it falls
|
|
1463
|
+
// through to the gateway's text command. Groups fall through too: changes are
|
|
1464
|
+
// direct-message only.
|
|
1465
|
+
async function pstackMenuRequest(chatId:string,userId:string,data:string) {
|
|
1466
|
+
if(!CALLBACK_URL_BASE)throw Error('not_configured')
|
|
1467
|
+
const response=await fetch(CALLBACK_URL_BASE+'/command',{method:'POST',headers:{'Content-Type':'application/json'},signal:AbortSignal.timeout(20000),body:JSON.stringify({command:'telegram_pstack',chat_id:chatId,payload:{user_id:userId,data}})})
|
|
1468
|
+
const result=await response.json() as {success?:boolean}
|
|
1469
|
+
if(!response.ok||!result.success)throw Error('unavailable')
|
|
1470
|
+
return pstackMenuMarkup(result)
|
|
1471
|
+
}
|
|
1472
|
+
bot.hears(PSTACK_MENU_COMMAND,async (ctx,next)=>{
|
|
1473
|
+
if(ctx.chat?.type!=='private'||!CALLBACK_URL_BASE)return next()
|
|
1474
|
+
if(!isCallbackAuthorized(ctx))return
|
|
1475
|
+
try{const menu=await pstackMenuRequest(String(ctx.chat.id),String(ctx.from!.id),'ps:h');await ctx.reply(menu.text,{reply_markup:menu.reply_markup})}
|
|
1476
|
+
catch{await ctx.reply('pstack setup unavailable. Please try /pstack_setup again.')}
|
|
1477
|
+
})
|
|
1478
|
+
|
|
1450
1479
|
async function taskStopRequest(chatId: string, userId: string, menuId?: string, index?: number) {
|
|
1451
1480
|
if (!CALLBACK_URL_BASE) throw new Error('not_configured')
|
|
1452
1481
|
const response=await fetch(CALLBACK_URL_BASE+'/command', {
|
|
@@ -1650,6 +1679,21 @@ bot.on('callback_query:data', async ctx => {
|
|
|
1650
1679
|
return
|
|
1651
1680
|
}
|
|
1652
1681
|
|
|
1682
|
+
// 🔁 Retry on a voice-note transcription failure: orch:vr:<input id> (44 bytes).
|
|
1683
|
+
const voiceRetry=/^orch:vr:([a-f0-9-]{36})$/.exec(data)
|
|
1684
|
+
if(voiceRetry){
|
|
1685
|
+
if(!ORCHESTRATION_ENABLED||ctx.callbackQuery.message?.chat.type!=='private'||!isCallbackAuthorized(ctx)){await ctx.answerCallbackQuery({text:'Not available or not authorized.'}).catch(()=>{});return}
|
|
1686
|
+
try{
|
|
1687
|
+
if(!CALLBACK_URL_BASE)throw Error('not_configured')
|
|
1688
|
+
const response=await fetch(CALLBACK_URL_BASE+'/command',{method:'POST',headers:{'Content-Type':'application/json'},signal:AbortSignal.timeout(10000),body:JSON.stringify({command:'telegram_voice_retry',chat_id:String(ctx.callbackQuery.message.chat.id),payload:{user_id:String(ctx.from.id),input_id:voiceRetry[1]}})})
|
|
1689
|
+
const result=await response.json() as {success?:boolean;text?:string;error?:string}
|
|
1690
|
+
await ctx.answerCallbackQuery({text:((response.ok&&result.success?result.text:result.error)??'Voice note cannot be retried.').slice(0,180)}).catch(()=>{})
|
|
1691
|
+
// Any answer settles this button: a retry was queued, or the note cannot be retried.
|
|
1692
|
+
if(response.ok&&result.success)await ctx.editMessageReplyMarkup({reply_markup:undefined}).catch(()=>{})
|
|
1693
|
+
}catch{await ctx.answerCallbackQuery({text:'Voice retry unavailable. Please send the voice note again.'}).catch(()=>{})}
|
|
1694
|
+
return
|
|
1695
|
+
}
|
|
1696
|
+
|
|
1653
1697
|
const voicePicker=/^(voicepick|voicepage|voicegroup|voicedismiss):([a-f0-9-]{36})(?::(male|female|neutral|unspecified|back))?(?::(\d+))?$/.exec(data)
|
|
1654
1698
|
if(voicePicker){
|
|
1655
1699
|
if(!ORCHESTRATION_ENABLED||ctx.callbackQuery.message?.chat.type!=='private'||!isCallbackAuthorized(ctx)){await ctx.answerCallbackQuery({text:'Not available or not authorized.'}).catch(()=>{});return}
|
|
@@ -1679,6 +1723,19 @@ bot.on('callback_query:data', async ctx => {
|
|
|
1679
1723
|
return
|
|
1680
1724
|
}
|
|
1681
1725
|
|
|
1726
|
+
if(data.startsWith('ps:')){
|
|
1727
|
+
if(ctx.callbackQuery.message?.chat.type!=='private'||!isCallbackAuthorized(ctx)){await ctx.answerCallbackQuery({text:'Not authorized.'}).catch(()=>{});return}
|
|
1728
|
+
try{
|
|
1729
|
+
const menu=await pstackMenuRequest(String(ctx.callbackQuery.message.chat.id),String(ctx.from.id),data)
|
|
1730
|
+
await ctx.answerCallbackQuery(menu.toast?{text:menu.toast}:undefined).catch(()=>{})
|
|
1731
|
+
if(menu.closed){await ctx.deleteMessage().catch(()=>{});return}
|
|
1732
|
+
// Turn on/off ends the menu with its result and no buttons, as a /voice choice does.
|
|
1733
|
+
if(menu.done){await confirmSelection(ctx,menu.text).catch(()=>{});return}
|
|
1734
|
+
await ctx.editMessageText(menu.text,{reply_markup:menu.reply_markup}).catch(()=>{})
|
|
1735
|
+
}catch{await ctx.answerCallbackQuery({text:'pstack setup unavailable. Use /pstack_setup again.'}).catch(()=>{})}
|
|
1736
|
+
return
|
|
1737
|
+
}
|
|
1738
|
+
|
|
1682
1739
|
const taskStop=/^taskstop:([a-f0-9-]{36}):(\d+)$/.exec(data)
|
|
1683
1740
|
if (taskStop) {
|
|
1684
1741
|
if (!ORCHESTRATION_ENABLED) { await ctx.answerCallbackQuery({text:'Task controls require orchestration mode.'}).catch(()=>{}); return }
|