@opengsd/gsd-pi 1.5.0-dev.4fb2d460 → 1.5.0-dev.c4c8885f
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/dist/resources/.managed-resources-content-hash +1 -1
- package/dist/resources/extensions/browser-tools/engine/managed-gsd-browser.js +114 -36
- package/dist/resources/extensions/gsd/activity-log.js +1 -1
- package/dist/resources/extensions/gsd/auto/orchestrator.js +16 -10
- package/dist/resources/extensions/gsd/auto-artifact-paths.js +2 -2
- package/dist/resources/extensions/gsd/auto-dispatch.js +53 -15
- package/dist/resources/extensions/gsd/auto-model-selection.js +28 -1
- package/dist/resources/extensions/gsd/auto-post-unit.js +4 -3
- package/dist/resources/extensions/gsd/auto-prompts.js +29 -117
- package/dist/resources/extensions/gsd/auto-start.js +53 -30
- package/dist/resources/extensions/gsd/auto-timeout-recovery.js +12 -2
- package/dist/resources/extensions/gsd/auto-timers.js +9 -2
- package/dist/resources/extensions/gsd/auto.js +97 -31
- package/dist/resources/extensions/gsd/compat/compat-marker.js +44 -0
- package/dist/resources/extensions/gsd/config-overlay.js +7 -2
- package/dist/resources/extensions/gsd/db/engine.js +33 -0
- package/dist/resources/extensions/gsd/db-adapter.js +30 -3
- package/dist/resources/extensions/gsd/docs/preferences-reference.md +3 -3
- package/dist/resources/extensions/gsd/journal.js +1 -1
- package/dist/resources/extensions/gsd/markdown-renderer.js +34 -91
- package/dist/resources/extensions/gsd/metrics.js +2 -2
- package/dist/resources/extensions/gsd/paths.js +70 -49
- package/dist/resources/extensions/gsd/post-unit-hooks.js +27 -0
- package/dist/resources/extensions/gsd/preferences-models.js +66 -15
- package/dist/resources/extensions/gsd/preferences-validation.js +66 -10
- package/dist/resources/extensions/gsd/rule-registry.js +106 -10
- package/dist/resources/extensions/gsd/state-reconciliation/drift/artifact-db.js +1 -10
- package/dist/resources/extensions/gsd/state-reconciliation/drift/completion.js +3 -24
- package/dist/resources/extensions/gsd/state-reconciliation/index.js +10 -0
- package/dist/resources/extensions/gsd/tools/complete-milestone.js +3 -5
- package/dist/resources/extensions/gsd/tools/reassess-roadmap.js +16 -10
- package/dist/resources/extensions/gsd/tools/validate-milestone.js +3 -8
- package/dist/resources/extensions/gsd/uat-dispatch.js +94 -0
- package/dist/resources/extensions/gsd/uok/audit-toggle.js +31 -2
- package/dist/resources/extensions/gsd/uok/audit.js +3 -0
- package/dist/resources/extensions/gsd/uok/gate-runner.js +22 -30
- package/dist/resources/extensions/gsd/uok/gitops.js +18 -15
- package/dist/resources/extensions/gsd/uok/kernel.js +120 -46
- package/dist/resources/extensions/gsd/uok/model-policy.js +17 -14
- package/dist/resources/extensions/gsd/workflow-event-ledger.js +1 -1
- package/dist/resources/extensions/gsd/workflow-logger.js +1 -1
- package/dist/resources/extensions/gsd/workflow-projections.js +9 -26
- package/dist/resources/extensions/gsd/workspace.js +5 -14
- package/dist/resources/extensions/shared/gsd-browser-cli.js +29 -0
- package/dist/tsconfig.extensions.tsbuildinfo +1 -1
- package/dist/web/standalone/.next/BUILD_ID +1 -1
- package/dist/web/standalone/.next/app-path-routes-manifest.json +10 -10
- package/dist/web/standalone/.next/build-manifest.json +2 -2
- package/dist/web/standalone/.next/prerender-manifest.json +3 -3
- package/dist/web/standalone/.next/server/app/_global-error.html +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.html +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/api/boot/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/bridge-terminal/input/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/bridge-terminal/resize/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/bridge-terminal/stream/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/captures/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/cleanup/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/doctor/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/export-data/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/files/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/forensics/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/git/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/history/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/hooks/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/inspect/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/knowledge/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/live-state/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/mcp-connections/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/notifications/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/onboarding/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/projects/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/recovery/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/session/browser/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/session/command/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/session/events/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/session/manage/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/settings-data/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/shutdown/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/skill-health/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/steer/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/switch-root/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/terminal/sessions/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/terminal/stream/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/undo/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/api/visualizer/route.js.nft.json +1 -1
- package/dist/web/standalone/.next/server/app/index.html +1 -1
- package/dist/web/standalone/.next/server/app/index.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/_full.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/_index.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- package/dist/web/standalone/.next/server/app-paths-manifest.json +10 -10
- package/dist/web/standalone/.next/server/chunks/{1128.js → 1991.js} +1 -1
- package/dist/web/standalone/.next/server/chunks/8357.js +1 -1
- package/dist/web/standalone/.next/server/middleware-build-manifest.js +1 -1
- package/dist/web/standalone/.next/server/pages/404.html +1 -1
- package/dist/web/standalone/.next/server/pages/500.html +1 -1
- package/dist/web/standalone/.next/server/server-reference-manifest.json +1 -1
- package/dist/worktree-cli-create.d.ts +10 -0
- package/dist/worktree-cli-create.js +11 -0
- package/dist/worktree-cli-format.d.ts +12 -0
- package/dist/worktree-cli-format.js +38 -0
- package/dist/worktree-cli-plan.d.ts +16 -0
- package/dist/worktree-cli-plan.js +19 -0
- package/dist/worktree-cli-session.d.ts +13 -0
- package/dist/worktree-cli-session.js +18 -0
- package/dist/worktree-cli-status.d.ts +35 -0
- package/dist/worktree-cli-status.js +54 -0
- package/dist/worktree-cli.d.ts +1 -16
- package/dist/worktree-cli.js +28 -122
- package/integrations/hermes/open_gsd_hermes/gsd_client.py +1 -1
- package/integrations/hermes/pyproject.toml +1 -1
- package/package.json +1 -1
- package/packages/cloud-mcp-gateway/package.json +2 -2
- package/packages/contracts/package.json +1 -1
- package/packages/daemon/dist/orchestrator-agent.d.ts +21 -0
- package/packages/daemon/dist/orchestrator-agent.d.ts.map +1 -0
- package/packages/daemon/dist/orchestrator-agent.js +113 -0
- package/packages/daemon/dist/orchestrator-agent.js.map +1 -0
- package/packages/daemon/dist/orchestrator-tools.d.ts +12 -0
- package/packages/daemon/dist/orchestrator-tools.d.ts.map +1 -0
- package/packages/daemon/dist/orchestrator-tools.js +137 -0
- package/packages/daemon/dist/orchestrator-tools.js.map +1 -0
- package/packages/daemon/dist/orchestrator.d.ts +4 -56
- package/packages/daemon/dist/orchestrator.d.ts.map +1 -1
- package/packages/daemon/dist/orchestrator.js +13 -303
- package/packages/daemon/dist/orchestrator.js.map +1 -1
- package/packages/daemon/dist/orchestrator.test.js +11 -1
- package/packages/daemon/dist/orchestrator.test.js.map +1 -1
- package/packages/daemon/package.json +4 -4
- package/packages/gsd-agent-core/package.json +5 -5
- package/packages/gsd-agent-modes/package.json +7 -7
- package/packages/mcp-server/package.json +4 -4
- package/packages/native/package.json +1 -1
- package/packages/pi-agent-core/package.json +1 -1
- package/packages/pi-ai/package.json +1 -1
- package/packages/pi-coding-agent/package.json +7 -7
- package/packages/pi-tui/package.json +2 -2
- package/packages/rpc-client/package.json +2 -2
- package/pkg/package.json +1 -1
- package/src/resources/extensions/browser-tools/engine/managed-gsd-browser.ts +146 -33
- package/src/resources/extensions/browser-tools/tests/gsd-browser-launch-config.test.mjs +25 -0
- package/src/resources/extensions/browser-tools/tests/managed-gsd-browser-tools.test.mjs +93 -0
- package/src/resources/extensions/gsd/activity-log.ts +1 -1
- package/src/resources/extensions/gsd/auto/orchestrator.ts +17 -11
- package/src/resources/extensions/gsd/auto-artifact-paths.ts +2 -1
- package/src/resources/extensions/gsd/auto-dispatch.ts +59 -14
- package/src/resources/extensions/gsd/auto-model-selection.ts +33 -1
- package/src/resources/extensions/gsd/auto-post-unit.ts +4 -2
- package/src/resources/extensions/gsd/auto-prompts.ts +53 -113
- package/src/resources/extensions/gsd/auto-start.ts +57 -28
- package/src/resources/extensions/gsd/auto-timeout-recovery.ts +12 -2
- package/src/resources/extensions/gsd/auto-timers.ts +9 -2
- package/src/resources/extensions/gsd/auto.ts +103 -30
- package/src/resources/extensions/gsd/compat/compat-marker.ts +47 -0
- package/src/resources/extensions/gsd/config-overlay.ts +7 -1
- package/src/resources/extensions/gsd/db/engine.ts +36 -0
- package/src/resources/extensions/gsd/db-adapter.ts +29 -3
- package/src/resources/extensions/gsd/docs/preferences-reference.md +3 -3
- package/src/resources/extensions/gsd/journal.ts +1 -1
- package/src/resources/extensions/gsd/markdown-renderer.ts +52 -103
- package/src/resources/extensions/gsd/metrics.ts +2 -2
- package/src/resources/extensions/gsd/paths.ts +87 -48
- package/src/resources/extensions/gsd/post-unit-hooks.ts +32 -0
- package/src/resources/extensions/gsd/preferences-models.ts +74 -20
- package/src/resources/extensions/gsd/preferences-types.ts +24 -1
- package/src/resources/extensions/gsd/preferences-validation.ts +77 -9
- package/src/resources/extensions/gsd/rule-registry.ts +111 -9
- package/src/resources/extensions/gsd/state-reconciliation/drift/artifact-db.ts +1 -9
- package/src/resources/extensions/gsd/state-reconciliation/drift/completion.ts +2 -22
- package/src/resources/extensions/gsd/state-reconciliation/index.ts +14 -0
- package/src/resources/extensions/gsd/tests/auto-orchestrator.test.ts +41 -2
- package/src/resources/extensions/gsd/tests/auto-post-unit-artifact-diagnostic.test.ts +48 -1
- package/src/resources/extensions/gsd/tests/auto-start-project-milestone-reconcile.test.ts +29 -1
- package/src/resources/extensions/gsd/tests/auto-timeout-recovery-supervisor-inflight-guard.test.ts +159 -0
- package/src/resources/extensions/gsd/tests/commands-verdict.test.ts +3 -1
- package/src/resources/extensions/gsd/tests/compat-marker.test.ts +85 -0
- package/src/resources/extensions/gsd/tests/complete-milestone.test.ts +45 -0
- package/src/resources/extensions/gsd/tests/db-adapter.test.ts +39 -0
- package/src/resources/extensions/gsd/tests/db-writable-probe.test.ts +66 -0
- package/src/resources/extensions/gsd/tests/flat-phase-renderer.test.ts +22 -1
- package/src/resources/extensions/gsd/tests/flat-phase-validation-path.test.ts +72 -32
- package/src/resources/extensions/gsd/tests/integration/paths.test.ts +88 -1
- package/src/resources/extensions/gsd/tests/milestone-closeout.test.ts +2 -1
- package/src/resources/extensions/gsd/tests/parsers-legacy-importers.test.ts +0 -1
- package/src/resources/extensions/gsd/tests/post-unit-hooks.test.ts +269 -0
- package/src/resources/extensions/gsd/tests/post-unit-retry-on-orchestrator-bridge.test.ts +8 -1
- package/src/resources/extensions/gsd/tests/read-uat-gate-verdict.test.ts +54 -0
- package/src/resources/extensions/gsd/tests/reassess-handler.test.ts +49 -1
- package/src/resources/extensions/gsd/tests/rule-registry.test.ts +95 -1
- package/src/resources/extensions/gsd/tests/sibling-model-fallbacks.test.ts +189 -0
- package/src/resources/extensions/gsd/tests/single-field-model-thinking.test.ts +156 -0
- package/src/resources/extensions/gsd/tests/skipped-validation-db-atomicity.test.ts +6 -1
- package/src/resources/extensions/gsd/tests/start-auto-detached.test.ts +32 -0
- package/src/resources/extensions/gsd/tests/supervisor-model-swap-inflight-guard.test.ts +181 -0
- package/src/resources/extensions/gsd/tests/supervisor-model-swap-thinking-clamp.test.ts +122 -0
- package/src/resources/extensions/gsd/tests/uat-dispatch.test.ts +211 -0
- package/src/resources/extensions/gsd/tests/uok-gate-runner.test.ts +39 -0
- package/src/resources/extensions/gsd/tests/uok-kernel-path.test.ts +226 -2
- package/src/resources/extensions/gsd/tests/uok-model-policy.test.ts +6 -0
- package/src/resources/extensions/gsd/tests/workflow-projections.test.ts +213 -2
- package/src/resources/extensions/gsd/tools/complete-milestone.ts +9 -5
- package/src/resources/extensions/gsd/tools/reassess-roadmap.ts +19 -8
- package/src/resources/extensions/gsd/tools/validate-milestone.ts +13 -9
- package/src/resources/extensions/gsd/types.ts +23 -4
- package/src/resources/extensions/gsd/uat-dispatch.ts +176 -0
- package/src/resources/extensions/gsd/uok/audit-toggle.ts +32 -2
- package/src/resources/extensions/gsd/uok/audit.ts +2 -0
- package/src/resources/extensions/gsd/uok/gate-runner.ts +26 -36
- package/src/resources/extensions/gsd/uok/gitops.ts +21 -18
- package/src/resources/extensions/gsd/uok/kernel.ts +169 -48
- package/src/resources/extensions/gsd/uok/model-policy.ts +20 -17
- package/src/resources/extensions/gsd/workflow-event-ledger.ts +1 -1
- package/src/resources/extensions/gsd/workflow-logger.ts +1 -1
- package/src/resources/extensions/gsd/workflow-projections.ts +9 -24
- package/src/resources/extensions/gsd/workspace.ts +5 -21
- package/src/resources/extensions/shared/gsd-browser-cli.ts +29 -0
- /package/dist/web/standalone/.next/static/{gXoWec4UNqcR0tkuHwYCr → NPMNi2HV8BuK3baQsEUhk}/_buildManifest.js +0 -0
- /package/dist/web/standalone/.next/static/{gXoWec4UNqcR0tkuHwYCr → NPMNi2HV8BuK3baQsEUhk}/_ssgManifest.js +0 -0
|
@@ -1,157 +1,26 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Orchestrator —
|
|
2
|
+
* Orchestrator — Discord-facing controller for the #gsd-control channel.
|
|
3
3
|
*
|
|
4
|
-
* Receives Discord messages,
|
|
5
|
-
*
|
|
6
|
-
* get_status, stop_session, get_session_detail), and sends the LLM's response
|
|
7
|
-
* back to Discord.
|
|
8
|
-
*
|
|
9
|
-
* Uses the standard messages.create() tool-use loop (not betaZodTool helpers,
|
|
10
|
-
* which don't exist in SDK v0.52). Zod schemas are used for input validation
|
|
11
|
-
* at the tool execution layer.
|
|
4
|
+
* Receives Discord messages, filters them by channel/owner/bot guards, delegates
|
|
5
|
+
* valid user content to OrchestratorAgent, and sends the response back to Discord.
|
|
12
6
|
*/
|
|
13
|
-
import {
|
|
14
|
-
// ---------------------------------------------------------------------------
|
|
15
|
-
// API key resolution — requires ANTHROPIC_API_KEY env var
|
|
16
|
-
// Anthropic OAuth removed per TOS compliance (see docs/user-docs/claude-code-auth-compliance.md)
|
|
17
|
-
// ---------------------------------------------------------------------------
|
|
18
|
-
function resolveAnthropicApiKey() {
|
|
19
|
-
const apiKey = process.env.ANTHROPIC_API_KEY;
|
|
20
|
-
if (!apiKey) {
|
|
21
|
-
throw new Error('ANTHROPIC_API_KEY is required. Set it in your environment or run `gsd config`.');
|
|
22
|
-
}
|
|
23
|
-
return apiKey;
|
|
24
|
-
}
|
|
25
|
-
// ---------------------------------------------------------------------------
|
|
26
|
-
// System Prompt
|
|
27
|
-
// ---------------------------------------------------------------------------
|
|
28
|
-
const SYSTEM_PROMPT = `You are GSD Control — a concise, capable orchestrator for managing GSD (Git Ship Done) coding agent sessions via Discord.
|
|
29
|
-
|
|
30
|
-
You have tools to list projects, start sessions, get status, stop sessions, and inspect session details. Use them to fulfill the user's requests.
|
|
31
|
-
|
|
32
|
-
Response guidelines:
|
|
33
|
-
- Be terse and direct. No filler, no performed enthusiasm.
|
|
34
|
-
- When reporting status, use bullet points with project name, status, duration, and cost.
|
|
35
|
-
- When starting a session, confirm with the project name and session ID.
|
|
36
|
-
- When stopping a session, confirm which session was stopped.
|
|
37
|
-
- If something fails, say what went wrong plainly.
|
|
38
|
-
- Use Discord markdown formatting (bold, code blocks) for readability.
|
|
39
|
-
- Never expose internal error stack traces to the user — summarize the issue.`;
|
|
40
|
-
// ---------------------------------------------------------------------------
|
|
41
|
-
// Tool Definitions (Anthropic API format)
|
|
42
|
-
// ---------------------------------------------------------------------------
|
|
43
|
-
const TOOLS = [
|
|
44
|
-
{
|
|
45
|
-
name: 'list_projects',
|
|
46
|
-
description: 'List all detected projects across configured scan roots. Returns project names, paths, and detected markers (git, node, gsd, etc.).',
|
|
47
|
-
input_schema: {
|
|
48
|
-
type: 'object',
|
|
49
|
-
properties: {},
|
|
50
|
-
required: [],
|
|
51
|
-
},
|
|
52
|
-
},
|
|
53
|
-
{
|
|
54
|
-
name: 'start_session',
|
|
55
|
-
description: 'Start a new GSD auto-mode session for a project. Provide the absolute project path. Optionally provide a command to run instead of the default "/gsd auto".',
|
|
56
|
-
input_schema: {
|
|
57
|
-
type: 'object',
|
|
58
|
-
properties: {
|
|
59
|
-
projectPath: { type: 'string', description: 'Absolute path to the project directory' },
|
|
60
|
-
command: { type: 'string', description: 'Optional command to send instead of "/gsd auto"' },
|
|
61
|
-
},
|
|
62
|
-
required: ['projectPath'],
|
|
63
|
-
},
|
|
64
|
-
},
|
|
65
|
-
{
|
|
66
|
-
name: 'get_status',
|
|
67
|
-
description: 'Get the current status of all active GSD sessions. Shows project name, status, duration, and cost for each.',
|
|
68
|
-
input_schema: {
|
|
69
|
-
type: 'object',
|
|
70
|
-
properties: {},
|
|
71
|
-
required: [],
|
|
72
|
-
},
|
|
73
|
-
},
|
|
74
|
-
{
|
|
75
|
-
name: 'stop_session',
|
|
76
|
-
description: 'Stop a running GSD session. Provide a session ID or project name — fuzzy matching is used to find the session.',
|
|
77
|
-
input_schema: {
|
|
78
|
-
type: 'object',
|
|
79
|
-
properties: {
|
|
80
|
-
identifier: { type: 'string', description: 'Session ID or project name to match' },
|
|
81
|
-
},
|
|
82
|
-
required: ['identifier'],
|
|
83
|
-
},
|
|
84
|
-
},
|
|
85
|
-
{
|
|
86
|
-
name: 'get_session_detail',
|
|
87
|
-
description: 'Get detailed information about a specific session including cost breakdown, recent events, pending blockers, and error state.',
|
|
88
|
-
input_schema: {
|
|
89
|
-
type: 'object',
|
|
90
|
-
properties: {
|
|
91
|
-
sessionId: { type: 'string', description: 'The session ID to inspect' },
|
|
92
|
-
},
|
|
93
|
-
required: ['sessionId'],
|
|
94
|
-
},
|
|
95
|
-
},
|
|
96
|
-
];
|
|
97
|
-
// ---------------------------------------------------------------------------
|
|
98
|
-
// Zod schemas for tool input validation
|
|
99
|
-
// ---------------------------------------------------------------------------
|
|
100
|
-
const StartSessionInput = z.object({
|
|
101
|
-
projectPath: z.string(),
|
|
102
|
-
command: z.string().optional(),
|
|
103
|
-
});
|
|
104
|
-
const StopSessionInput = z.object({
|
|
105
|
-
identifier: z.string(),
|
|
106
|
-
});
|
|
107
|
-
const GetSessionDetailInput = z.object({
|
|
108
|
-
sessionId: z.string(),
|
|
109
|
-
});
|
|
110
|
-
// ---------------------------------------------------------------------------
|
|
111
|
-
// Conversation History Cap
|
|
112
|
-
// ---------------------------------------------------------------------------
|
|
113
|
-
const MAX_HISTORY = 30;
|
|
114
|
-
// ---------------------------------------------------------------------------
|
|
115
|
-
// Orchestrator
|
|
116
|
-
// ---------------------------------------------------------------------------
|
|
7
|
+
import { OrchestratorAgent } from './orchestrator-agent.js';
|
|
117
8
|
export class Orchestrator {
|
|
118
9
|
deps;
|
|
119
|
-
|
|
120
|
-
history = [];
|
|
121
|
-
/**
|
|
122
|
-
* @param deps - orchestrator dependencies (session manager, channel manager, etc.)
|
|
123
|
-
* @param client - optional Anthropic client for testability; if omitted, created from env
|
|
124
|
-
*/
|
|
10
|
+
agent;
|
|
125
11
|
constructor(deps, client) {
|
|
126
12
|
this.deps = deps;
|
|
127
|
-
this.
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
*/
|
|
133
|
-
async getClient() {
|
|
134
|
-
if (this.client)
|
|
135
|
-
return this.client;
|
|
136
|
-
const apiKey = resolveAnthropicApiKey();
|
|
137
|
-
const { default: AnthropicSDK } = await import('@anthropic-ai/sdk');
|
|
138
|
-
this.client = new AnthropicSDK({ apiKey });
|
|
139
|
-
return this.client;
|
|
13
|
+
this.agent = new OrchestratorAgent({ model: deps.config.model, max_tokens: deps.config.max_tokens }, {
|
|
14
|
+
sessionManager: deps.sessionManager,
|
|
15
|
+
scanProjects: deps.scanProjects,
|
|
16
|
+
logger: deps.logger,
|
|
17
|
+
}, client);
|
|
140
18
|
}
|
|
141
|
-
/**
|
|
142
|
-
* Handle an incoming Discord message. Entry point called by the bot's
|
|
143
|
-
* message handler for every message in every channel.
|
|
144
|
-
*
|
|
145
|
-
* Guards: ignores bot messages, non-owner messages, and non-control-channel messages.
|
|
146
|
-
*/
|
|
147
19
|
async handleMessage(message) {
|
|
148
|
-
// Ignore bot messages
|
|
149
20
|
if (message.author.bot)
|
|
150
21
|
return;
|
|
151
|
-
// Ignore non-control-channel messages
|
|
152
22
|
if (message.channelId !== this.deps.config.control_channel_id)
|
|
153
23
|
return;
|
|
154
|
-
// Auth guard — only the owner can use the orchestrator
|
|
155
24
|
if (message.author.id !== this.deps.ownerId) {
|
|
156
25
|
this.deps.logger.debug('orchestrator auth rejected', { userId: message.author.id });
|
|
157
26
|
return;
|
|
@@ -164,13 +33,9 @@ export class Orchestrator {
|
|
|
164
33
|
channelId: message.channelId,
|
|
165
34
|
contentLength: content.length,
|
|
166
35
|
});
|
|
167
|
-
// Append user message to history
|
|
168
|
-
this.history.push({ role: 'user', content });
|
|
169
36
|
try {
|
|
170
|
-
// Show typing indicator while processing
|
|
171
37
|
await message.channel.sendTyping().catch(() => { });
|
|
172
|
-
const responseText = await this.
|
|
173
|
-
// Send response to Discord
|
|
38
|
+
const responseText = await this.agent.run(content);
|
|
174
39
|
await message.channel.send(responseText);
|
|
175
40
|
this.deps.logger.info('orchestrator response sent', {
|
|
176
41
|
channelId: message.channelId,
|
|
@@ -179,16 +44,11 @@ export class Orchestrator {
|
|
|
179
44
|
}
|
|
180
45
|
catch (err) {
|
|
181
46
|
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
182
|
-
// Invalidate cached client on auth errors so next call re-resolves OAuth token
|
|
183
|
-
if (errorMsg.includes('authentication') || errorMsg.includes('apiKey') || errorMsg.includes('authToken') || errorMsg.includes('401')) {
|
|
184
|
-
this.client = null;
|
|
185
|
-
}
|
|
186
47
|
this.deps.logger.error('orchestrator error', {
|
|
187
48
|
error: errorMsg,
|
|
188
49
|
userId: message.author.id,
|
|
189
50
|
channelId: message.channelId,
|
|
190
51
|
});
|
|
191
|
-
// Send error feedback to Discord
|
|
192
52
|
try {
|
|
193
53
|
await message.channel.send('⚠️ Something went wrong processing your request.');
|
|
194
54
|
}
|
|
@@ -197,163 +57,13 @@ export class Orchestrator {
|
|
|
197
57
|
error: sendErr instanceof Error ? sendErr.message : String(sendErr),
|
|
198
58
|
});
|
|
199
59
|
}
|
|
200
|
-
// Still append a synthetic assistant message so history stays paired
|
|
201
|
-
this.history.push({ role: 'assistant', content: '[error — see logs]' });
|
|
202
|
-
}
|
|
203
|
-
this.trimHistory();
|
|
204
|
-
}
|
|
205
|
-
/**
|
|
206
|
-
* Run the tool-use loop: call messages.create(), execute any tool calls,
|
|
207
|
-
* feed results back, repeat until the model produces a final text response.
|
|
208
|
-
*/
|
|
209
|
-
async runAgentLoop() {
|
|
210
|
-
const client = await this.getClient();
|
|
211
|
-
const { model, max_tokens } = this.deps.config;
|
|
212
|
-
let loopMessages = [...this.history];
|
|
213
|
-
const maxIterations = 10; // safety valve
|
|
214
|
-
for (let i = 0; i < maxIterations; i++) {
|
|
215
|
-
const response = await client.messages.create({
|
|
216
|
-
model,
|
|
217
|
-
max_tokens,
|
|
218
|
-
system: SYSTEM_PROMPT,
|
|
219
|
-
tools: TOOLS,
|
|
220
|
-
messages: loopMessages,
|
|
221
|
-
});
|
|
222
|
-
// If the model stopped for end_turn (no tool calls), extract text and return
|
|
223
|
-
if (response.stop_reason === 'end_turn' || response.stop_reason !== 'tool_use') {
|
|
224
|
-
const textBlocks = response.content.filter((b) => b.type === 'text');
|
|
225
|
-
const finalText = textBlocks.map((b) => b.text).join('\n') || '(No response)';
|
|
226
|
-
// Append assistant message to conversation history
|
|
227
|
-
this.history.push({ role: 'assistant', content: finalText });
|
|
228
|
-
return finalText;
|
|
229
|
-
}
|
|
230
|
-
// Model wants to use tools — execute them all
|
|
231
|
-
const toolUseBlocks = response.content.filter((b) => b.type === 'tool_use');
|
|
232
|
-
// Build tool results
|
|
233
|
-
const toolResults = [];
|
|
234
|
-
for (const toolUse of toolUseBlocks) {
|
|
235
|
-
const result = await this.executeTool(toolUse.name, toolUse.input);
|
|
236
|
-
toolResults.push({
|
|
237
|
-
type: 'tool_result',
|
|
238
|
-
tool_use_id: toolUse.id,
|
|
239
|
-
content: result,
|
|
240
|
-
});
|
|
241
|
-
}
|
|
242
|
-
// Append the assistant message (with tool_use blocks) and user tool_result message
|
|
243
|
-
loopMessages = [
|
|
244
|
-
...loopMessages,
|
|
245
|
-
{ role: 'assistant', content: response.content },
|
|
246
|
-
{ role: 'user', content: toolResults },
|
|
247
|
-
];
|
|
248
|
-
}
|
|
249
|
-
// If we hit max iterations, return a fallback
|
|
250
|
-
return 'I hit the maximum number of tool iterations. Please try a simpler request.';
|
|
251
|
-
}
|
|
252
|
-
/**
|
|
253
|
-
* Execute a single tool by name. Returns a string result for the LLM.
|
|
254
|
-
* All errors are caught and returned as error strings (the LLM can reason about them).
|
|
255
|
-
*/
|
|
256
|
-
async executeTool(name, input) {
|
|
257
|
-
try {
|
|
258
|
-
switch (name) {
|
|
259
|
-
case 'list_projects':
|
|
260
|
-
return await this.toolListProjects();
|
|
261
|
-
case 'start_session':
|
|
262
|
-
return await this.toolStartSession(input);
|
|
263
|
-
case 'get_status':
|
|
264
|
-
return this.toolGetStatus();
|
|
265
|
-
case 'get_session_detail':
|
|
266
|
-
return this.toolGetSessionDetail(input);
|
|
267
|
-
case 'stop_session':
|
|
268
|
-
return await this.toolStopSession(input);
|
|
269
|
-
default:
|
|
270
|
-
return `Unknown tool: ${name}`;
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
catch (err) {
|
|
274
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
275
|
-
this.deps.logger.error('tool execution error', { tool: name, error: msg });
|
|
276
|
-
return `Error: ${msg}`;
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
// ---------------------------------------------------------------------------
|
|
280
|
-
// Tool implementations
|
|
281
|
-
// ---------------------------------------------------------------------------
|
|
282
|
-
async toolListProjects() {
|
|
283
|
-
const projects = await this.deps.scanProjects();
|
|
284
|
-
if (projects.length === 0)
|
|
285
|
-
return 'No projects found.';
|
|
286
|
-
return JSON.stringify(projects.map((p) => ({ name: p.name, path: p.path, markers: p.markers })), null, 2);
|
|
287
|
-
}
|
|
288
|
-
async toolStartSession(input) {
|
|
289
|
-
const parsed = StartSessionInput.parse(input);
|
|
290
|
-
const sessionId = await this.deps.sessionManager.startSession({
|
|
291
|
-
projectDir: parsed.projectPath,
|
|
292
|
-
command: parsed.command,
|
|
293
|
-
});
|
|
294
|
-
return `Session started: ${sessionId} for ${parsed.projectPath}`;
|
|
295
|
-
}
|
|
296
|
-
toolGetStatus() {
|
|
297
|
-
const sessions = this.deps.sessionManager.getAllSessions();
|
|
298
|
-
if (sessions.length === 0)
|
|
299
|
-
return 'No active sessions.';
|
|
300
|
-
return sessions
|
|
301
|
-
.map((s) => {
|
|
302
|
-
const durationMin = Math.floor((Date.now() - s.startTime) / 60_000);
|
|
303
|
-
const cost = s.cost.totalCost.toFixed(4);
|
|
304
|
-
return `• ${s.projectName} — ${s.status} (${durationMin}m, $${cost})`;
|
|
305
|
-
})
|
|
306
|
-
.join('\n');
|
|
307
|
-
}
|
|
308
|
-
async toolStopSession(input) {
|
|
309
|
-
const parsed = StopSessionInput.parse(input);
|
|
310
|
-
const { identifier } = parsed;
|
|
311
|
-
// Try exact sessionId match first
|
|
312
|
-
const byId = this.deps.sessionManager.getSession(identifier);
|
|
313
|
-
if (byId) {
|
|
314
|
-
await this.deps.sessionManager.cancelSession(identifier);
|
|
315
|
-
return `Stopped session ${identifier} (${byId.projectName})`;
|
|
316
|
-
}
|
|
317
|
-
// Fuzzy match by project name
|
|
318
|
-
const all = this.deps.sessionManager.getAllSessions();
|
|
319
|
-
const match = all.find((s) => s.projectName.toLowerCase().includes(identifier.toLowerCase()) ||
|
|
320
|
-
s.projectDir.toLowerCase().includes(identifier.toLowerCase()));
|
|
321
|
-
if (match) {
|
|
322
|
-
await this.deps.sessionManager.cancelSession(match.sessionId);
|
|
323
|
-
return `Stopped session ${match.sessionId} (${match.projectName})`;
|
|
324
|
-
}
|
|
325
|
-
return `No session found matching "${identifier}"`;
|
|
326
|
-
}
|
|
327
|
-
toolGetSessionDetail(input) {
|
|
328
|
-
const parsed = GetSessionDetailInput.parse(input);
|
|
329
|
-
const result = this.deps.sessionManager.getResult(parsed.sessionId);
|
|
330
|
-
return JSON.stringify(result, null, 2);
|
|
331
|
-
}
|
|
332
|
-
// ---------------------------------------------------------------------------
|
|
333
|
-
// History management
|
|
334
|
-
// ---------------------------------------------------------------------------
|
|
335
|
-
/**
|
|
336
|
-
* Trim conversation history to MAX_HISTORY entries.
|
|
337
|
-
* Removes the oldest user+assistant pair from the front to keep pairs aligned.
|
|
338
|
-
*/
|
|
339
|
-
trimHistory() {
|
|
340
|
-
while (this.history.length > MAX_HISTORY) {
|
|
341
|
-
// Remove from front — two messages at a time to keep user/assistant pairs
|
|
342
|
-
this.history.splice(0, 2);
|
|
343
60
|
}
|
|
344
61
|
}
|
|
345
|
-
/**
|
|
346
|
-
* Return a copy of the conversation history (for debugging / observability).
|
|
347
|
-
*/
|
|
348
62
|
getHistory() {
|
|
349
|
-
return
|
|
63
|
+
return this.agent.getHistory();
|
|
350
64
|
}
|
|
351
|
-
/**
|
|
352
|
-
* Stop the orchestrator — clears history and nulls client reference.
|
|
353
|
-
*/
|
|
354
65
|
stop() {
|
|
355
|
-
this.
|
|
356
|
-
this.client = null;
|
|
66
|
+
this.agent.stop();
|
|
357
67
|
}
|
|
358
68
|
}
|
|
359
69
|
//# sourceMappingURL=orchestrator.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orchestrator.js","sourceRoot":"","sources":["../src/orchestrator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAexB,8EAA8E;AAC9E,0DAA0D;AAC1D,iGAAiG;AACjG,8EAA8E;AAE9E,SAAS,sBAAsB;IAC7B,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC;IAC7C,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CACb,gFAAgF,CACjF,CAAC;IACJ,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAqBD,8EAA8E;AAC9E,gBAAgB;AAChB,8EAA8E;AAE9E,MAAM,aAAa,GAAG;;;;;;;;;;;8EAWwD,CAAC;AAE/E,8EAA8E;AAC9E,0CAA0C;AAC1C,8EAA8E;AAE9E,MAAM,KAAK,GAAW;IACpB;QACE,IAAI,EAAE,eAAe;QACrB,WAAW,EAAE,qIAAqI;QAClJ,YAAY,EAAE;YACZ,IAAI,EAAE,QAAiB;YACvB,UAAU,EAAE,EAAE;YACd,QAAQ,EAAE,EAAE;SACb;KACF;IACD;QACE,IAAI,EAAE,eAAe;QACrB,WAAW,EAAE,6JAA6J;QAC1K,YAAY,EAAE;YACZ,IAAI,EAAE,QAAiB;YACvB,UAAU,EAAE;gBACV,WAAW,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,wCAAwC,EAAE;gBACtF,OAAO,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,iDAAiD,EAAE;aAC5F;YACD,QAAQ,EAAE,CAAC,aAAa,CAAC;SAC1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CAAC,cAAc,CAAC,SAAS,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QACpE,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IACzC,CAAC;IAED,8EAA8E;IAC9E,qBAAqB;IACrB,8EAA8E;IAE9E;;;OAGG;IACK,WAAW;QACjB,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,WAAW,EAAE,CAAC;YACzC,0EAA0E;YAC1E,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QAC5B,CAAC;IACH,CAAC;IAED;;OAEG;IACH,UAAU;QACR,OAAO,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC;IAC3B,CAAC;IAED;;OAEG;IACH,IAAI;QACF,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;QAClB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;IACrB,CAAC;CACF","sourcesContent":["/**\n * Orchestrator — LLM-powered agent for the #gsd-control Discord channel.\n *\n * Receives Discord messages, maintains conversation history, calls the\n * Anthropic messages API with 5 tool definitions (list_projects, start_session,\n * get_status, stop_session, get_session_detail), and sends the LLM's response\n * back to Discord.\n *\n * Uses the standard messages.create() tool-use loop (not betaZodTool helpers,\n * which don't exist in SDK v0.52). Zod schemas are used for input validation\n * at the tool execution layer.\n */\n\nimport { z } from 'zod';\nimport type Anthropic from '@anthropic-ai/sdk';\nimport type {\n MessageParam,\n ContentBlockParam,\n Tool,\n ToolResultBlockParam,\n ToolUseBlock,\n TextBlock,\n} from '@anthropic-ai/sdk/resources/messages/messages';\nimport type { SessionManager } from './session-manager.js';\nimport type { ChannelManager } from './channel-manager.js';\nimport type { ProjectInfo, ManagedSession } from './types.js';\nimport type { Logger } from './logger.js';\n\n// ---------------------------------------------------------------------------\n// API key resolution — requires ANTHROPIC_API_KEY env var\n// Anthropic OAuth removed per TOS compliance (see docs/user-docs/claude-code-auth-compliance.md)\n// ---------------------------------------------------------------------------\n\nfunction resolveAnthropicApiKey(): string {\n const apiKey = process.env.ANTHROPIC_API_KEY;\n if (!apiKey) {\n throw new Error(\n 'ANTHROPIC_API_KEY is required. Set it in your environment or run `gsd config`.',\n );\n }\n return apiKey;\n}\n\n// ---------------------------------------------------------------------------\n// Configuration\n// ---------------------------------------------------------------------------\n\nexport interface OrchestratorConfig {\n model: string;\n max_tokens: number;\n control_channel_id: string;\n}\n\nexport interface OrchestratorDeps {\n sessionManager: SessionManager;\n channelManager: ChannelManager;\n scanProjects: () => Promise<ProjectInfo[]>;\n config: OrchestratorConfig;\n logger: Logger;\n ownerId: string;\n}\n\n// ---------------------------------------------------------------------------\n// System Prompt\n// ---------------------------------------------------------------------------\n\nconst SYSTEM_PROMPT = `You are GSD Control — a concise, capable orchestrator for managing GSD (Git Ship Done) coding agent sessions via Discord.\n\nYou have tools to list projects, start sessions, get status, stop sessions, and inspect session details. Use them to fulfill the user's requests.\n\nResponse guidelines:\n- Be terse and direct. No filler, no performed enthusiasm.\n- When reporting status, use bullet points with project name, status, duration, and cost.\n- When starting a session, confirm with the project name and session ID.\n- When stopping a session, confirm which session was stopped.\n- If something fails, say what went wrong plainly.\n- Use Discord markdown formatting (bold, code blocks) for readability.\n- Never expose internal error stack traces to the user — summarize the issue.`;\n\n// ---------------------------------------------------------------------------\n// Tool Definitions (Anthropic API format)\n// ---------------------------------------------------------------------------\n\nconst TOOLS: Tool[] = [\n {\n name: 'list_projects',\n description: 'List all detected projects across configured scan roots. Returns project names, paths, and detected markers (git, node, gsd, etc.).',\n input_schema: {\n type: 'object' as const,\n properties: {},\n required: [],\n },\n },\n {\n name: 'start_session',\n description: 'Start a new GSD auto-mode session for a project. Provide the absolute project path. Optionally provide a command to run instead of the default \"/gsd auto\".',\n input_schema: {\n type: 'object' as const,\n properties: {\n projectPath: { type: 'string', description: 'Absolute path to the project directory' },\n command: { type: 'string', description: 'Optional command to send instead of \"/gsd auto\"' },\n },\n required: ['projectPath'],\n },\n },\n {\n name: 'get_status',\n description: 'Get the current status of all active GSD sessions. Shows project name, status, duration, and cost for each.',\n input_schema: {\n type: 'object' as const,\n properties: {},\n required: [],\n },\n },\n {\n name: 'stop_session',\n description: 'Stop a running GSD session. Provide a session ID or project name — fuzzy matching is used to find the session.',\n input_schema: {\n type: 'object' as const,\n properties: {\n identifier: { type: 'string', description: 'Session ID or project name to match' },\n },\n required: ['identifier'],\n },\n },\n {\n name: 'get_session_detail',\n description: 'Get detailed information about a specific session including cost breakdown, recent events, pending blockers, and error state.',\n input_schema: {\n type: 'object' as const,\n properties: {\n sessionId: { type: 'string', description: 'The session ID to inspect' },\n },\n required: ['sessionId'],\n },\n },\n];\n\n// ---------------------------------------------------------------------------\n// Zod schemas for tool input validation\n// ---------------------------------------------------------------------------\n\nconst StartSessionInput = z.object({\n projectPath: z.string(),\n command: z.string().optional(),\n});\n\nconst StopSessionInput = z.object({\n identifier: z.string(),\n});\n\nconst GetSessionDetailInput = z.object({\n sessionId: z.string(),\n});\n\n// ---------------------------------------------------------------------------\n// Conversation History Cap\n// ---------------------------------------------------------------------------\n\nconst MAX_HISTORY = 30;\n\n// ---------------------------------------------------------------------------\n// Orchestrator\n// ---------------------------------------------------------------------------\n\nexport class Orchestrator {\n private readonly deps: OrchestratorDeps;\n private client: Anthropic | null;\n private history: MessageParam[] = [];\n\n /**\n * @param deps - orchestrator dependencies (session manager, channel manager, etc.)\n * @param client - optional Anthropic client for testability; if omitted, created from env\n */\n constructor(deps: OrchestratorDeps, client?: Anthropic) {\n this.deps = deps;\n this.client = client ?? null;\n }\n\n /**\n * Lazily initialise the Anthropic client. Dynamic import handles K007 module resolution.\n * Requires ANTHROPIC_API_KEY environment variable.\n */\n private async getClient(): Promise<Anthropic> {\n if (this.client) return this.client;\n const apiKey = resolveAnthropicApiKey();\n const { default: AnthropicSDK } = await import('@anthropic-ai/sdk');\n this.client = new AnthropicSDK({ apiKey });\n return this.client;\n }\n\n /**\n * Handle an incoming Discord message. Entry point called by the bot's\n * message handler for every message in every channel.\n *\n * Guards: ignores bot messages, non-owner messages, and non-control-channel messages.\n */\n async handleMessage(message: DiscordMessageLike): Promise<void> {\n // Ignore bot messages\n if (message.author.bot) return;\n\n // Ignore non-control-channel messages\n if (message.channelId !== this.deps.config.control_channel_id) return;\n\n // Auth guard — only the owner can use the orchestrator\n if (message.author.id !== this.deps.ownerId) {\n this.deps.logger.debug('orchestrator auth rejected', { userId: message.author.id });\n return;\n }\n\n const content = message.content?.trim();\n if (!content) return;\n\n this.deps.logger.info('orchestrator message received', {\n userId: message.author.id,\n channelId: message.channelId,\n contentLength: content.length,\n });\n\n // Append user message to history\n this.history.push({ role: 'user', content });\n\n try {\n // Show typing indicator while processing\n await message.channel.sendTyping().catch(() => {});\n\n const responseText = await this.runAgentLoop();\n\n // Send response to Discord\n await message.channel.send(responseText);\n\n this.deps.logger.info('orchestrator response sent', {\n channelId: message.channelId,\n responseLength: responseText.length,\n });\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n\n // Invalidate cached client on auth errors so next call re-resolves OAuth token\n if (errorMsg.includes('authentication') || errorMsg.includes('apiKey') || errorMsg.includes('authToken') || errorMsg.includes('401')) {\n this.client = null;\n }\n\n this.deps.logger.error('orchestrator error', {\n error: errorMsg,\n userId: message.author.id,\n channelId: message.channelId,\n });\n\n // Send error feedback to Discord\n try {\n await message.channel.send('⚠️ Something went wrong processing your request.');\n } catch (sendErr) {\n this.deps.logger.warn('orchestrator error reply failed', {\n error: sendErr instanceof Error ? sendErr.message : String(sendErr),\n });\n }\n\n // Still append a synthetic assistant message so history stays paired\n this.history.push({ role: 'assistant', content: '[error — see logs]' });\n }\n\n this.trimHistory();\n }\n\n /**\n * Run the tool-use loop: call messages.create(), execute any tool calls,\n * feed results back, repeat until the model produces a final text response.\n */\n private async runAgentLoop(): Promise<string> {\n const client = await this.getClient();\n const { model, max_tokens } = this.deps.config;\n\n let loopMessages: MessageParam[] = [...this.history];\n const maxIterations = 10; // safety valve\n\n for (let i = 0; i < maxIterations; i++) {\n const response = await client.messages.create({\n model,\n max_tokens,\n system: SYSTEM_PROMPT,\n tools: TOOLS,\n messages: loopMessages,\n });\n\n // If the model stopped for end_turn (no tool calls), extract text and return\n if (response.stop_reason === 'end_turn' || response.stop_reason !== 'tool_use') {\n const textBlocks = response.content.filter(\n (b): b is TextBlock => b.type === 'text',\n );\n const finalText = textBlocks.map((b) => b.text).join('\\n') || '(No response)';\n\n // Append assistant message to conversation history\n this.history.push({ role: 'assistant', content: finalText });\n\n return finalText;\n }\n\n // Model wants to use tools — execute them all\n const toolUseBlocks = response.content.filter(\n (b): b is ToolUseBlock => b.type === 'tool_use',\n );\n\n // Build tool results\n const toolResults: ToolResultBlockParam[] = [];\n for (const toolUse of toolUseBlocks) {\n const result = await this.executeTool(toolUse.name, toolUse.input as Record<string, unknown>);\n toolResults.push({\n type: 'tool_result',\n tool_use_id: toolUse.id,\n content: result,\n });\n }\n\n // Append the assistant message (with tool_use blocks) and user tool_result message\n loopMessages = [\n ...loopMessages,\n { role: 'assistant', content: response.content as ContentBlockParam[] },\n { role: 'user', content: toolResults },\n ];\n }\n\n // If we hit max iterations, return a fallback\n return 'I hit the maximum number of tool iterations. Please try a simpler request.';\n }\n\n /**\n * Execute a single tool by name. Returns a string result for the LLM.\n * All errors are caught and returned as error strings (the LLM can reason about them).\n */\n private async executeTool(name: string, input: Record<string, unknown>): Promise<string> {\n try {\n switch (name) {\n case 'list_projects':\n return await this.toolListProjects();\n case 'start_session':\n return await this.toolStartSession(input);\n case 'get_status':\n return this.toolGetStatus();\n case 'get_session_detail':\n return this.toolGetSessionDetail(input);\n case 'stop_session':\n return await this.toolStopSession(input);\n default:\n return `Unknown tool: ${name}`;\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.deps.logger.error('tool execution error', { tool: name, error: msg });\n return `Error: ${msg}`;\n }\n }\n\n // ---------------------------------------------------------------------------\n // Tool implementations\n // ---------------------------------------------------------------------------\n\n private async toolListProjects(): Promise<string> {\n const projects = await this.deps.scanProjects();\n if (projects.length === 0) return 'No projects found.';\n return JSON.stringify(\n projects.map((p) => ({ name: p.name, path: p.path, markers: p.markers })),\n null,\n 2,\n );\n }\n\n private async toolStartSession(input: Record<string, unknown>): Promise<string> {\n const parsed = StartSessionInput.parse(input);\n const sessionId = await this.deps.sessionManager.startSession({\n projectDir: parsed.projectPath,\n command: parsed.command,\n });\n return `Session started: ${sessionId} for ${parsed.projectPath}`;\n }\n\n private toolGetStatus(): string {\n const sessions = this.deps.sessionManager.getAllSessions();\n if (sessions.length === 0) return 'No active sessions.';\n\n return sessions\n .map((s: ManagedSession) => {\n const durationMin = Math.floor((Date.now() - s.startTime) / 60_000);\n const cost = s.cost.totalCost.toFixed(4);\n return `• ${s.projectName} — ${s.status} (${durationMin}m, $${cost})`;\n })\n .join('\\n');\n }\n\n private async toolStopSession(input: Record<string, unknown>): Promise<string> {\n const parsed = StopSessionInput.parse(input);\n const { identifier } = parsed;\n\n // Try exact sessionId match first\n const byId = this.deps.sessionManager.getSession(identifier);\n if (byId) {\n await this.deps.sessionManager.cancelSession(identifier);\n return `Stopped session ${identifier} (${byId.projectName})`;\n }\n\n // Fuzzy match by project name\n const all = this.deps.sessionManager.getAllSessions();\n const match = all.find(\n (s: ManagedSession) =>\n s.projectName.toLowerCase().includes(identifier.toLowerCase()) ||\n s.projectDir.toLowerCase().includes(identifier.toLowerCase()),\n );\n if (match) {\n await this.deps.sessionManager.cancelSession(match.sessionId);\n return `Stopped session ${match.sessionId} (${match.projectName})`;\n }\n\n return `No session found matching \"${identifier}\"`;\n }\n\n private toolGetSessionDetail(input: Record<string, unknown>): string {\n const parsed = GetSessionDetailInput.parse(input);\n const result = this.deps.sessionManager.getResult(parsed.sessionId);\n return JSON.stringify(result, null, 2);\n }\n\n // ---------------------------------------------------------------------------\n // History management\n // ---------------------------------------------------------------------------\n\n /**\n * Trim conversation history to MAX_HISTORY entries.\n * Removes the oldest user+assistant pair from the front to keep pairs aligned.\n */\n private trimHistory(): void {\n while (this.history.length > MAX_HISTORY) {\n // Remove from front — two messages at a time to keep user/assistant pairs\n this.history.splice(0, 2);\n }\n }\n\n /**\n * Return a copy of the conversation history (for debugging / observability).\n */\n getHistory(): MessageParam[] {\n return [...this.history];\n }\n\n /**\n * Stop the orchestrator — clears history and nulls client reference.\n */\n stop(): void {\n this.history = [];\n this.client = null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Discord message type (minimal interface for testability)\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal Discord message interface — avoids importing discord.js directly,\n * making the orchestrator testable without full discord.js mocking.\n */\nexport interface DiscordMessageLike {\n author: { id: string; bot: boolean };\n channelId: string;\n content: string;\n channel: {\n send: (content: string) => Promise<unknown>;\n sendTyping: () => Promise<unknown>;\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"orchestrator.js","sourceRoot":"","sources":["../src/orchestrator.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAQH,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAiB5D,MAAM,OAAO,YAAY;IACN,IAAI,CAAmB;IACvB,KAAK,CAAoB;IAE1C,YAAY,IAAsB,EAAE,MAAkB;QACpD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,IAAI,iBAAiB,CAChC,EAAE,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE,EAChE;YACE,cAAc,EAAE,IAAI,CAAC,cAAc;YACnC,YAAY,EAAE,IAAI,CAAC,YAAY;YAC/B,MAAM,EAAE,IAAI,CAAC,MAAM;SACpB,EACD,MAAM,CACP,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,OAA2B;QAC7C,IAAI,OAAO,CAAC,MAAM,CAAC,GAAG;YAAE,OAAO;QAC/B,IAAI,OAAO,CA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C;YAElE,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,oBAAoB,EAAE;gBAC3C,KAAK,EAAE,QAAQ;gBACf,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE;gBACzB,SAAS,EAAE,OAAO,CAAC,SAAS;aAC7B,CAAC,CAAC;YAEH,IAAI,CAAC;gBACH,MAAM,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,kDAAkD,CAAC,CAAC;YACjF,CAAC;YAAC,OAAO,OAAO,EAAE,CAAC;gBACjB,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,iCAAiC,EAAE;oBACvD,KAAK,EAAE,OAAO,YAAY,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC;iBACpE,CAAC,CAAC;YACL,CAAC;QACH,CAAC;IACH,CAAC;IAED,UAAU;QACR,OAAO,IAAI,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC;IACjC,CAAC;IAED,IAAI;QACF,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;IACpB,CAAC;CACF","sourcesContent":["/**\n * Orchestrator — Discord-facing controller for the #gsd-control channel.\n *\n * Receives Discord messages, filters them by channel/owner/bot guards, delegates\n * valid user content to OrchestratorAgent, and sends the response back to Discord.\n */\n\nimport type Anthropic from '@anthropic-ai/sdk';\nimport type { MessageParam } from '@anthropic-ai/sdk/resources/messages/messages';\nimport type { SessionManager } from './session-manager.js';\nimport type { ChannelManager } from './channel-manager.js';\nimport type { ProjectInfo } from './types.js';\nimport type { Logger } from './logger.js';\nimport { OrchestratorAgent } from './orchestrator-agent.js';\n\nexport interface OrchestratorConfig {\n model: string;\n max_tokens: number;\n control_channel_id: string;\n}\n\nexport interface OrchestratorDeps {\n sessionManager: SessionManager;\n channelManager: ChannelManager;\n scanProjects: () => Promise<ProjectInfo[]>;\n config: OrchestratorConfig;\n logger: Logger;\n ownerId: string;\n}\n\nexport class Orchestrator {\n private readonly deps: OrchestratorDeps;\n private readonly agent: OrchestratorAgent;\n\n constructor(deps: OrchestratorDeps, client?: Anthropic) {\n this.deps = deps;\n this.agent = new OrchestratorAgent(\n { model: deps.config.model, max_tokens: deps.config.max_tokens },\n {\n sessionManager: deps.sessionManager,\n scanProjects: deps.scanProjects,\n logger: deps.logger,\n },\n client,\n );\n }\n\n async handleMessage(message: DiscordMessageLike): Promise<void> {\n if (message.author.bot) return;\n if (message.channelId !== this.deps.config.control_channel_id) return;\n\n if (message.author.id !== this.deps.ownerId) {\n this.deps.logger.debug('orchestrator auth rejected', { userId: message.author.id });\n return;\n }\n\n const content = message.content?.trim();\n if (!content) return;\n\n this.deps.logger.info('orchestrator message received', {\n userId: message.author.id,\n channelId: message.channelId,\n contentLength: content.length,\n });\n\n try {\n await message.channel.sendTyping().catch(() => {});\n\n const responseText = await this.agent.run(content);\n await message.channel.send(responseText);\n\n this.deps.logger.info('orchestrator response sent', {\n channelId: message.channelId,\n responseLength: responseText.length,\n });\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n\n this.deps.logger.error('orchestrator error', {\n error: errorMsg,\n userId: message.author.id,\n channelId: message.channelId,\n });\n\n try {\n await message.channel.send('⚠️ Something went wrong processing your request.');\n } catch (sendErr) {\n this.deps.logger.warn('orchestrator error reply failed', {\n error: sendErr instanceof Error ? sendErr.message : String(sendErr),\n });\n }\n }\n }\n\n getHistory(): MessageParam[] {\n return this.agent.getHistory();\n }\n\n stop(): void {\n this.agent.stop();\n }\n}\n\nexport interface DiscordMessageLike {\n author: { id: string; bot: boolean };\n channelId: string;\n content: string;\n channel: {\n send: (content: string) => Promise<unknown>;\n sendTyping: () => Promise<unknown>;\n };\n}\n"]}
|
|
@@ -234,8 +234,18 @@ describe('Orchestrator', () => {
|
|
|
234
234
|
await orchestrator.handleMessage(msg);
|
|
235
235
|
assert.equal(msg.sentMessages.length, 1);
|
|
236
236
|
assert.equal(msg.sentMessages[0], 'Here are your projects');
|
|
237
|
-
// The tool was called (2 create calls: tool_use + end_turn)
|
|
238
237
|
assert.equal(mockClient.createCallCount, 2);
|
|
238
|
+
const finalMessages = mockClient.lastCreateParams?.messages;
|
|
239
|
+
const toolResultMessage = finalMessages.at(-1);
|
|
240
|
+
assert.equal(toolResultMessage?.role, 'user');
|
|
241
|
+
const toolResults = toolResultMessage?.content;
|
|
242
|
+
assert.equal(toolResults.length, 1);
|
|
243
|
+
assert.match(toolResults[0].tool_use_id, /^toolu_/);
|
|
244
|
+
assert.equal(toolResults[0].type, 'tool_result');
|
|
245
|
+
assert.equal(toolResults[0].content, JSON.stringify([
|
|
246
|
+
{ name: 'alpha', path: '/home/user/alpha', markers: ['git', 'node', 'gsd'] },
|
|
247
|
+
{ name: 'bravo', path: '/home/user/bravo', markers: ['git', 'rust'] },
|
|
248
|
+
], null, 2));
|
|
239
249
|
});
|
|
240
250
|
});
|
|
241
251
|
// ---- start_session tool ----
|