@desplega.ai/agent-swarm 1.161.0 → 1.162.0
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 +3 -2
- package/dist/{acp-adapter-xx489vvb.js → acp-adapter-74m73ae9.js} +1 -1
- package/dist/{actions-ykjkn0m9.js → actions-4sr14gnt.js} +34 -31
- package/dist/{anthropic-messages-5qx80j9k.js → anthropic-messages-8xxrzky9.js} +22 -26
- package/dist/{app-0hdqa4k1.js → app-pt68fbwp.js} +13 -11
- package/dist/{artifact-3v5t9jtg.js → artifact-fey7dvj9.js} +3 -2
- package/dist/{assistant-am2g5g8a.js → assistant-cv3jytks.js} +37 -34
- package/dist/{azure-openai-responses-fszbkp0e.js → azure-openai-responses-f5cqsyj8.js} +15 -10
- package/dist/{boot-reembed-xy9t7avg.js → boot-reembed-4ht4gqth.js} +13 -11
- package/dist/{boot-reembed-gt5gjkt4.js → boot-reembed-nxpcvpj9.js} +12 -10
- package/dist/{boot-scrub-logs-9x0985y5.js → boot-scrub-logs-k93kyw8k.js} +9 -7
- package/dist/{boot-seeds-trv0d4vg.js → boot-seeds-1skcrs0e.js} +13 -10
- package/dist/{claude-adapter-jb6e1e54.js → claude-adapter-r5g0tzge.js} +23 -20
- package/dist/{claude-managed-setup-d1q9hv2b.js → claude-managed-setup-pkyrgshb.js} +3 -2
- package/dist/{claude-sdk-session-zga700s2.js → claude-sdk-session-jxyxnrwd.js} +5565 -5512
- package/dist/{cli-we0q7t0e.js → cli-2zy95vhm.js} +137 -64
- package/dist/{cli-35pj2yva.js → cli-4cwxn7gp.js} +38 -11
- package/dist/{cli-ad4qxm6j.js → cli-4dcpaefp.js} +2 -2
- package/dist/{cli-82c1pacn.js → cli-4x0csdjq.js} +71 -37
- package/dist/{cli-sqm3r5ps.js → cli-5bcd7sfy.js} +14 -18
- package/dist/{cli-d56tgd45.js → cli-5k6k8ta3.js} +2 -2
- package/dist/{cli-1er0rhz8.js → cli-5xhpb3kv.js} +15 -15
- package/dist/{cli-yrg7c73k.js → cli-7af8yhav.js} +10 -183
- package/dist/{cli-r6fsxc76.js → cli-7tre70zp.js} +513 -961
- package/dist/{cli-bh7jed3k.js → cli-8ev9xqnx.js} +34 -18
- package/dist/cli-bsky8g7w.js +449 -0
- package/dist/{cli-hn04t9db.js → cli-cebmgwsc.js} +14 -10
- package/dist/{cli-cfkrztza.js → cli-cvatsam7.js} +2 -2
- package/dist/{cli-2658f6at.js → cli-cvk6yzw5.js} +6 -8
- package/dist/{cli-ptr8h7kp.js → cli-eg0b3p0k.js} +5 -218
- package/dist/{cli-zb6xbk61.js → cli-g739zqzt.js} +4 -4
- package/dist/{cli-dv6cdjs2.js → cli-gd4favx9.js} +28 -7
- package/dist/{cli-5p3x4zna.js → cli-gpqpmns7.js} +2 -2
- package/dist/{cli-5nbmpy8w.js → cli-hb5c2x5y.js} +1 -1
- package/dist/{cli-jpf7e1zq.js → cli-hmsw1gpy.js} +3 -3
- package/dist/{cli-1cz0c18q.js → cli-jf7wmv1r.js} +2521 -733
- package/dist/{cli-qwsnmjdd.js → cli-jxs2ygaw.js} +168 -61
- package/dist/cli-kdkwd3yr.js +615 -0
- package/dist/{cli-hgmnf38m.js → cli-kh04eqwe.js} +1 -1
- package/dist/{cli-0383bp7f.js → cli-kp42yek0.js} +425 -90
- package/dist/{cli-ybgv4kw2.js → cli-mbssg1xv.js} +9 -2
- package/dist/{cli-jsp14b6c.js → cli-mzfth0bp.js} +38 -1
- package/dist/{cli-8g6mc14k.js → cli-nq7yqw7b.js} +16 -5
- package/dist/{cli-ee8bc46j.js → cli-nt8hecg9.js} +33 -32
- package/dist/{cli-9s68w752.js → cli-p0r8sxj5.js} +1 -1
- package/dist/{cli-58e8yr0d.js → cli-pkd6s2wy.js} +4 -2
- package/dist/{cli-17xpf7cm.js → cli-q24re23n.js} +6 -4
- package/dist/cli-qjjvzwzd.js +222 -0
- package/dist/cli-qrgt5bqf.js +189 -0
- package/dist/{cli-et8m9xsv.js → cli-rfjw9jw2.js} +22 -10
- package/dist/{cli-798vkbks.js → cli-rj0gqwwp.js} +2 -2
- package/dist/{cli-121ph74b.js → cli-rnyzn44p.js} +1 -1
- package/dist/{cli-vnnz5ncg.js → cli-s3hwpt9v.js} +95 -16
- package/dist/{cli-7119ja3w.js → cli-sptrj5f5.js} +2 -2
- package/dist/{cli-a8c82p2t.js → cli-sqvfa090.js} +13 -6
- package/dist/{cli-phfg8vy8.js → cli-swfmp1fx.js} +26 -26
- package/dist/{cli-nsdxtcbg.js → cli-tcen9p5w.js} +8 -5
- package/dist/{cli-9m03pzga.js → cli-vc9bp061.js} +5 -5
- package/dist/{cli-rtx9dygp.js → cli-vxe6qa4h.js} +1 -1
- package/dist/{cli-ecfxwnyb.js → cli-vy3ed88x.js} +1 -1
- package/dist/{cli-0c7ata9h.js → cli-vyqs9ya8.js} +6 -6
- package/dist/cli-wbvnn6tk.js +861 -0
- package/dist/{cli-kgd3p0bm.js → cli-wjgs5wxe.js} +6 -6
- package/dist/cli-wxkkd0e0.js +33 -0
- package/dist/{cli-akfj32vj.js → cli-xqpk3rp7.js} +5 -4
- package/dist/cli-zp38xvtm.js +9487 -0
- package/dist/{cli-3zc55ctx.js → cli-zvhd3f64.js} +2 -2
- package/dist/{cli-ze1d3wzv.js → cli-zxqx25nz.js} +5 -5
- package/dist/cli.js +32 -25
- package/dist/{cloudflare-workers-ai-system-one-k6fbxw9d.js → cloudflare-workers-ai-system-one-k8ddqjkq.js} +8 -6
- package/dist/{codex-adapter-04v97vep.js → codex-adapter-esvmnhn7.js} +13 -13
- package/dist/{codex-hook-20me6byw.js → codex-hook-m73jmqgx.js} +19 -3
- package/dist/{codex-session-runner-ax69mqq3.js → codex-session-runner-ban9excr.js} +13 -13
- package/dist/{commands-18gy08n1.js → commands-75413p2n.js} +9 -7
- package/dist/{db-d2pvjpyt.js → db-7f5pecwg.js} +11 -7
- package/dist/{dispatcher-8wbwyzjg.js → dispatcher-fh9at8nz.js} +33 -30
- package/dist/{dsh-adapter-ysqk9snv.js → dsh-adapter-wpze65d4.js} +3 -3
- package/dist/{e2b-esmt1r16.js → e2b-gjgdjp91.js} +10 -9
- package/dist/{pi-logo-animation-e9a0t68z.js → easter-egg-3d-3w5c2n4c.js} +122 -68
- package/dist/{execute-cmagrbrz.js → execute-f50wg9nh.js} +29 -6
- package/dist/{google-generative-ai-k6n5nbpp.js → google-generative-ai-jxxpnegy.js} +2 -2
- package/dist/{google-vertex-44xxtcvp.js → google-vertex-x7q1angm.js} +5 -5
- package/dist/{handlers-6b69m5kp.js → handlers-w13787bb.js} +36 -33
- package/dist/{hook-srnkt0hb.js → hook-46g1jrvx.js} +28 -15
- package/dist/{hook-k3mydf2n.js → hook-4tpts2ry.js} +20 -17
- package/dist/{http-hrf80ca1.js → http-19pzbfrt.js} +964 -176
- package/dist/{index-9rxdvj6w.js → index-8fd4dm4h.js} +34 -31
- package/dist/{index-1asbaj62.js → index-dqmp15bq.js} +35 -32
- package/dist/{index-45evq4ee.js → index-qb4q1y3e.js} +33 -30
- package/dist/{index-k4nj18qs.js → index-s75wc4wd.js} +12 -10
- package/dist/{index-xmevk2b9.js → index-scptvdxg.js} +27 -25
- package/dist/{keepalive-sfdz6ksp.js → keepalive-xa5ts9cd.js} +11 -9
- package/dist/{lead-ej91e9hw.js → lead-qp4xkvjq.js} +45 -41
- package/dist/{maintenance-80dnd7ke.js → maintenance-rm5885hm.js} +13 -11
- package/dist/{mistral-conversations-pc3ntnxt.js → mistral-conversations-rw7fbt22.js} +4 -4
- package/dist/{node-a5e00qhp.js → node-8zkdq42h.js} +834 -833
- package/dist/{oauth-refresh-sweep-m1etk2mx.js → oauth-refresh-sweep-1csdfebf.js} +10 -8
- package/dist/{onboard-0q8sdfqc.js → onboard-r6b78cs4.js} +10 -10
- package/dist/{openai-codex-responses-n7n683p2.js → openai-codex-responses-efvrgrq3.js} +4 -4
- package/dist/{openai-completions-jpaj5g2b.js → openai-completions-bbbrrz4z.js} +12 -8
- package/dist/{openai-responses-9a3nme9j.js → openai-responses-9jjyrcm1.js} +15 -10
- package/dist/{opencode-adapter-4wcgmvgf.js → opencode-adapter-kb3g6pkf.js} +2 -2
- package/dist/{otel-impl-hnqm9mxq.js → otel-impl-0y9knpky.js} +5 -5
- package/dist/{pi-mono-adapter-d6sqm9wr.js → pi-mono-adapter-z6s1bme2.js} +100 -19
- package/dist/{pricing-refresh-y60z64pm.js → pricing-refresh-mth26tgp.js} +11 -9
- package/dist/{rbac-roles-8pa0754b.js → rbac-roles-kwntb23q.js} +13 -9
- package/dist/rbac-roles-vpk4ebm8.js +45 -0
- package/dist/{registry-v5wytg0s.js → registry-km6t1jd2.js} +1 -1
- package/dist/{render-v2-418s1vj7.js → render-v2-hcm7h00y.js} +13 -11
- package/dist/{runtime-3pknc168.js → runtime-vfjsfsc5.js} +4 -4
- package/dist/{setup-yghdkj4x.js → setup-hbyzd65h.js} +2 -2
- package/dist/{virtual-modules-jcceevt5.js → virtual-modules-9bv7ry91.js} +9 -8
- package/dist/{work-objects-j1sz20v9.js → work-objects-m09sxnhe.js} +36 -33
- package/dist/{worker-d4gcvkjt.js → worker-0h35rvk4.js} +45 -41
- package/openapi.json +491 -12
- package/package.json +13 -6
- package/src/be/api-drain.ts +184 -0
- package/src/be/db/tasks/read.ts +31 -6
- package/src/be/db/tasks/write.ts +5 -4
- package/src/be/db.ts +42 -18
- package/src/be/memory/link-resolver.ts +29 -3
- package/src/be/migrations/192_favorites_agent_fs_path.sql +36 -0
- package/src/be/onboarding.ts +7 -1
- package/src/be/seed-prompt-templates.ts +1 -0
- package/src/be/swarm-config-guard.ts +35 -16
- package/src/be/task-citations.ts +11 -5
- package/src/be/users.ts +3 -0
- package/src/cli.tsx +3 -2
- package/src/comb/agent-fs.ts +39 -0
- package/src/comb/config.ts +37 -0
- package/src/comb/markers.ts +37 -0
- package/src/comb/review-batch.ts +486 -0
- package/src/comb/templates.ts +88 -0
- package/src/commands/context-preamble.ts +4 -1
- package/src/commands/hook.ts +2 -1
- package/src/commands/runner.ts +262 -68
- package/src/commands/templates.ts +10 -0
- package/src/extensions/contract-types.generated.ts +1 -1
- package/src/fs/agent-fs-provider.ts +106 -2
- package/src/heartbeat/heartbeat.ts +4 -0
- package/src/hooks/codex-hook.ts +25 -1
- package/src/hooks/hook.ts +13 -0
- package/src/hooks/pr-body-guard.ts +983 -0
- package/src/http/all-routes.ts +1 -0
- package/src/http/assets.ts +5 -17
- package/src/http/comb.ts +131 -0
- package/src/http/core.ts +2 -1
- package/src/http/fs.ts +9 -17
- package/src/http/index.ts +23 -9
- package/src/http/onboarding.ts +21 -2
- package/src/http/poll.ts +30 -3
- package/src/http/realtime.ts +62 -0
- package/src/http/request-principal.ts +22 -0
- package/src/http/status.ts +34 -2
- package/src/kv-reserved-namespaces.ts +10 -5
- package/src/providers/dsh-adapter.ts +1 -1
- package/src/providers/pi-mono-adapter.ts +123 -0
- package/src/rbac/legacy-policy.ts +1 -0
- package/src/rbac/permissions.ts +4 -0
- package/src/realtime/auth.ts +63 -1
- package/src/realtime/tickets.ts +52 -0
- package/src/realtime/transport.ts +51 -22
- package/src/scripts-runtime/types/swarm-extension.d.ts +3 -1
- package/src/telemetry-context.ts +175 -0
- package/src/telemetry-contract/EVENTS.md +81 -0
- package/src/telemetry-contract/SOURCE.json +9 -0
- package/src/telemetry-contract/catalog.json +1335 -0
- package/src/telemetry-contract/index.ts +60 -0
- package/src/telemetry-contract/types.gen.ts +1971 -0
- package/src/telemetry-identity.ts +129 -0
- package/src/telemetry-snapshot.ts +211 -0
- package/src/telemetry-trigger.ts +125 -0
- package/src/telemetry-types.typetest.ts +40 -0
- package/src/telemetry.ts +271 -67
- package/src/tests/api-drain-e2e.test.ts +249 -0
- package/src/tests/api-drain-worker-e2e.test.ts +216 -0
- package/src/tests/api-drain.test.ts +351 -0
- package/src/tests/comb-config-guard.test.ts +38 -0
- package/src/tests/comb-links.test.ts +162 -0
- package/src/tests/comb-markers.test.ts +68 -0
- package/src/tests/comb-review-batch.test.ts +770 -0
- package/src/tests/comb-status.test.ts +152 -0
- package/src/tests/db-task-read-contract.test.ts +2 -0
- package/src/tests/db-task-write-contract.test.ts +1 -0
- package/src/tests/docs-index-footprint.test.js +3 -3
- package/src/tests/dsh-adapter.test.ts +1 -1
- package/src/tests/favorites-agent-fs-path.test.ts +226 -0
- package/src/tests/memory-link-resolver.test.ts +34 -0
- package/src/tests/onboarding.test.ts +108 -0
- package/src/tests/pi-mono-adapter.test.ts +265 -2
- package/src/tests/pr-body-leaks.test.ts +789 -0
- package/src/tests/preload.ts +8 -0
- package/src/tests/rbac-engine.test.ts +19 -0
- package/src/tests/realtime-room-auth.test.ts +104 -1
- package/src/tests/realtime-tickets.test.ts +74 -0
- package/src/tests/realtime-transport.test.ts +131 -4
- package/src/tests/runner-api-drain.test.ts +301 -0
- package/src/tests/runner-fallback-output.test.ts +61 -0
- package/src/tests/runner-fenced-json-output.test.ts +178 -0
- package/src/tests/script-connections.test.ts +2 -0
- package/src/tests/send-task-requested-by.test.ts +133 -15
- package/src/tests/task-lifecycle-telemetry.test.ts +8 -3
- package/src/tests/telemetry-context.test.ts +314 -0
- package/src/tests/telemetry-init.test.ts +51 -19
- package/src/tests/telemetry-snapshot.test.ts +229 -0
- package/src/tests/telemetry-trigger.test.ts +200 -0
- package/src/tests/template-registry-helpers.ts +1 -0
- package/src/tests/workflow-agent-task-retry.test.ts +363 -0
- package/src/tests/workflow-definition-telemetry.test.ts +4 -4
- package/src/tools/poll-task.ts +20 -1
- package/src/tools/send-task.ts +9 -1
- package/src/tools/task-action.ts +11 -0
- package/src/types.ts +2 -1
- package/src/utils/api-drain.ts +24 -0
- package/src/utils/constants.ts +57 -16
- package/src/utils/pr-body-leaks.ts +172 -0
- package/src/utils/task-attachment-links.ts +14 -8
- package/src/workflows/recovery.ts +26 -1
- package/src/workflows/resume.ts +31 -4
- package/src/workflows/task-step-routing.ts +75 -2
- package/tsconfig.json +3 -0
- package/dist/cli-tjf4cn8z.js +0 -9119
- package/dist/cli-tsk3nz8a.js +0 -582
- package/dist/{cli-t6v2ah3r.js → cli-twrh04ap.js} +3 -3
package/src/http/status.ts
CHANGED
|
@@ -34,6 +34,8 @@ import {
|
|
|
34
34
|
NOT_EXTENSION_AGENT_SQL,
|
|
35
35
|
} from "../be/db";
|
|
36
36
|
import { getEmbeddingProvider } from "../be/memory";
|
|
37
|
+
import { getCombServiceUserId } from "../comb/agent-fs";
|
|
38
|
+
import { getCombConfig } from "../comb/config";
|
|
37
39
|
import { getFileStorageProvider } from "../fs/registry";
|
|
38
40
|
import { getSlackConfiguration } from "../slack/config";
|
|
39
41
|
import { getSlackConnectionState } from "../slack/connection-state";
|
|
@@ -120,6 +122,16 @@ export const StatusActivitySchema = z.object({
|
|
|
120
122
|
});
|
|
121
123
|
export type StatusActivity = z.infer<typeof StatusActivitySchema>;
|
|
122
124
|
|
|
125
|
+
export const StatusCombSchema = z.object({
|
|
126
|
+
enabled: z.boolean(),
|
|
127
|
+
api_url: z.string().nullable(),
|
|
128
|
+
live_url: z.string(),
|
|
129
|
+
org_id: z.string().nullable(),
|
|
130
|
+
drive_id: z.string().nullable(),
|
|
131
|
+
/** agent-fs user id of the swarm service account, which writes Comb's "sent" replies. */
|
|
132
|
+
service_user_id: z.string().nullable(),
|
|
133
|
+
});
|
|
134
|
+
|
|
123
135
|
/**
|
|
124
136
|
* Effective telemetry opt-out state (`ANONYMIZED_TELEMETRY`, on by default).
|
|
125
137
|
* The dashboard reads it to stop its own browser-side notification events when
|
|
@@ -135,6 +147,8 @@ export const StatusAgentFsSchema = z.object({
|
|
|
135
147
|
base_url: z.string().nullable(),
|
|
136
148
|
provider_id: z.string(),
|
|
137
149
|
capabilities: z.record(z.string(), z.unknown()),
|
|
150
|
+
/** Comb, the agent-fs review space in the dashboard. */
|
|
151
|
+
comb: StatusCombSchema,
|
|
138
152
|
});
|
|
139
153
|
export type StatusAgentFs = z.infer<typeof StatusAgentFsSchema>;
|
|
140
154
|
|
|
@@ -686,6 +700,10 @@ export function computeHealth(setup: SetupMilestone[]): StatusHealth {
|
|
|
686
700
|
// ─── Public payload builder (also exported for tests) ────────────────────────
|
|
687
701
|
|
|
688
702
|
export async function buildStatusPayload(): Promise<StatusResponse> {
|
|
703
|
+
// step-9: the agent-fs identity lookup (at most 2 s) runs while the DB work below does.
|
|
704
|
+
const combServiceUserId = getCombConfig().enabled
|
|
705
|
+
? getCombServiceUserId()
|
|
706
|
+
: Promise.resolve(null);
|
|
689
707
|
const automationSetup = await getAutomationSetupStates();
|
|
690
708
|
const setup = await buildSetup(automationSetup);
|
|
691
709
|
const automationInputs = await listEnabledAutomationPreflightInputs();
|
|
@@ -694,14 +712,16 @@ export async function buildStatusPayload(): Promise<StatusResponse> {
|
|
|
694
712
|
const automations: AutomationStatus[] = automationInputs
|
|
695
713
|
.map((automation) => toStatus(preflightAutomation(automation, automationSetup)))
|
|
696
714
|
.sort((a, b) => a.name.localeCompare(b.name) || a.kind.localeCompare(b.kind));
|
|
715
|
+
const activity = await getInstanceActivity();
|
|
697
716
|
return {
|
|
698
717
|
identity: buildIdentity(),
|
|
699
718
|
setup,
|
|
700
|
-
activity
|
|
719
|
+
activity,
|
|
701
720
|
agent_fs: {
|
|
702
721
|
configured: !!process.env.AGENT_FS_API_URL,
|
|
703
722
|
base_url: process.env.AGENT_FS_API_URL ?? null,
|
|
704
723
|
...getAgentFsStatusProvider(),
|
|
724
|
+
comb: getCombStatus(await combServiceUserId),
|
|
705
725
|
},
|
|
706
726
|
automations,
|
|
707
727
|
health: computeHealth(setup),
|
|
@@ -709,6 +729,18 @@ export async function buildStatusPayload(): Promise<StatusResponse> {
|
|
|
709
729
|
};
|
|
710
730
|
}
|
|
711
731
|
|
|
732
|
+
function getCombStatus(serviceUserId: string | null): StatusAgentFs["comb"] {
|
|
733
|
+
const comb = getCombConfig();
|
|
734
|
+
return {
|
|
735
|
+
enabled: comb.enabled,
|
|
736
|
+
api_url: comb.apiUrl,
|
|
737
|
+
live_url: comb.liveUrl,
|
|
738
|
+
org_id: comb.orgId,
|
|
739
|
+
drive_id: comb.driveId,
|
|
740
|
+
service_user_id: comb.enabled ? serviceUserId : null,
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
|
|
712
744
|
function getAgentFsStatusProvider(): {
|
|
713
745
|
provider_id: string;
|
|
714
746
|
capabilities: Record<string, unknown>;
|
|
@@ -735,7 +767,7 @@ const getStatus = route({
|
|
|
735
767
|
pattern: ["status"],
|
|
736
768
|
summary: "Identity + setup readiness + live activity for the swarm dashboard",
|
|
737
769
|
description:
|
|
738
|
-
"Single source of truth consumed by the UI home page. Identity comes from SWARM_* envs; setup milestones each emit `unverified | configured | verified`; automations report `running | needs_setup` from the same runtime preflight used at dispatch; activity counts agents alive in the last 5 min and tasks created in the last 24h; agent_fs reports whether AGENT_FS_API_URL is set; telemetry reports the effective ANONYMIZED_TELEMETRY opt-out state.",
|
|
770
|
+
"Single source of truth consumed by the UI home page. Identity comes from SWARM_* envs; setup milestones each emit `unverified | configured | verified`; automations report `running | needs_setup` from the same runtime preflight used at dispatch; activity counts agents alive in the last 5 min and tasks created in the last 24h; agent_fs reports whether AGENT_FS_API_URL is set, plus the Comb settings (COMB_ENABLED, the browser-facing agent-fs URL, the shared org and drive ids, and the agent-fs user id of the swarm service account); telemetry reports the effective ANONYMIZED_TELEMETRY opt-out state.",
|
|
739
771
|
tags: ["Status"],
|
|
740
772
|
responses: {
|
|
741
773
|
200: { description: "Status payload", schema: StatusResponseSchema },
|
|
@@ -1,16 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Namespace families owned by internal subsystems which write through the raw
|
|
3
3
|
* DB helpers. Generic HTTP/MCP KV callers may read these namespaces for
|
|
4
|
-
* inspection, but must not mutate them.
|
|
4
|
+
* inspection, but must not mutate them. A family is `<name>` and `<name>:*`,
|
|
5
|
+
* mapped here to the error a generic write gets.
|
|
5
6
|
*/
|
|
7
|
+
const RESERVED_FAMILIES = new Map([
|
|
8
|
+
["apps", "namespace is reserved for swarm apps; use the app row endpoints"],
|
|
9
|
+
// step-9: Comb's "Send to swarm" claims (`comb:sent`).
|
|
10
|
+
["comb", "namespace is reserved for Comb; use POST /api/comb/review-batches"],
|
|
11
|
+
]);
|
|
12
|
+
|
|
6
13
|
export function isReservedNamespace(namespace: string): boolean {
|
|
7
|
-
return namespace
|
|
14
|
+
return reservedNamespaceError(namespace) !== null;
|
|
8
15
|
}
|
|
9
16
|
|
|
10
17
|
export function reservedNamespaceError(namespace: string): string | null {
|
|
11
|
-
return
|
|
12
|
-
? "namespace is reserved for swarm apps; use the app row endpoints"
|
|
13
|
-
: null;
|
|
18
|
+
return RESERVED_FAMILIES.get(namespace.split(":", 1)[0] ?? "") ?? null;
|
|
14
19
|
}
|
|
15
20
|
|
|
16
21
|
export function reservedRoomKeyError(key: string): string | null {
|
|
@@ -34,7 +34,7 @@ import type {
|
|
|
34
34
|
} from "./types";
|
|
35
35
|
|
|
36
36
|
// npm's `latest` is older and lacks the JSON/stdin contract used here.
|
|
37
|
-
export const DSH_PACKAGE = "@deepseek-ai/dsh@0.2.
|
|
37
|
+
export const DSH_PACKAGE = "@deepseek-ai/dsh@0.2.1-alpha.1";
|
|
38
38
|
|
|
39
39
|
export function checkDshCredentials(env: Record<string, string | undefined>): CredStatus {
|
|
40
40
|
return env.DEEPSEEK_API_KEY?.trim() || env.OPENROUTER_API_KEY?.trim()
|
|
@@ -35,6 +35,9 @@ import {
|
|
|
35
35
|
} from "@earendil-works/pi-coding-agent";
|
|
36
36
|
import { type TSchema, Type } from "typebox";
|
|
37
37
|
import "./pi-codemode-runtime";
|
|
38
|
+
// Registers the reprompt template in the code registry (the runner loads it too).
|
|
39
|
+
import "../commands/templates";
|
|
40
|
+
import { resolveTemplateAsync } from "../prompts/resolver";
|
|
38
41
|
import { CORE_TOOLS } from "../tools/tool-config";
|
|
39
42
|
import { classifyAwsSdkError } from "../utils/aws-error-classifier";
|
|
40
43
|
import { parseEnvFlag } from "../utils/env-flag";
|
|
@@ -747,6 +750,40 @@ export function extractPiAssistantText(message: unknown): string {
|
|
|
747
750
|
return extractTextContent(msg.content);
|
|
748
751
|
}
|
|
749
752
|
|
|
753
|
+
/** What one assistant `message_end` carried, by block type only (never content). */
|
|
754
|
+
interface AssistantTurnShape {
|
|
755
|
+
stopReason?: string;
|
|
756
|
+
blockTypes: string[];
|
|
757
|
+
outputTokens?: number;
|
|
758
|
+
hasText: boolean;
|
|
759
|
+
hasToolCall: boolean;
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/** Keep log labels to short identifier-like tokens so a log line can never carry content. */
|
|
763
|
+
function safeLabel(value: unknown): string {
|
|
764
|
+
return typeof value === "string" && /^[A-Za-z0-9_-]{1,32}$/.test(value) ? value : "other";
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
function describeAssistantTurn(message: unknown): AssistantTurnShape {
|
|
768
|
+
const msg = (message ?? {}) as {
|
|
769
|
+
content?: unknown;
|
|
770
|
+
stopReason?: unknown;
|
|
771
|
+
usage?: { output?: unknown };
|
|
772
|
+
};
|
|
773
|
+
const blocks = Array.isArray(msg.content) ? msg.content : [];
|
|
774
|
+
const blockTypes = blocks.map((b) => safeLabel((b as { type?: unknown } | null)?.type));
|
|
775
|
+
const output = msg.usage?.output;
|
|
776
|
+
return {
|
|
777
|
+
stopReason: typeof msg.stopReason === "string" ? safeLabel(msg.stopReason) : undefined,
|
|
778
|
+
blockTypes: typeof msg.content === "string" && msg.content.trim() ? ["text"] : blockTypes,
|
|
779
|
+
outputTokens: typeof output === "number" ? output : undefined,
|
|
780
|
+
hasText: extractTextContent(msg.content) !== "",
|
|
781
|
+
hasToolCall: blockTypes.includes("toolCall"),
|
|
782
|
+
};
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
const TERMINAL_STORE_PROGRESS_STATUSES = new Set(["completed", "failed"]);
|
|
786
|
+
|
|
750
787
|
export class PiMonoSession implements ProviderSession {
|
|
751
788
|
private listeners: Array<(event: ProviderEvent) => void> = [];
|
|
752
789
|
private eventQueue: ProviderEvent[] = [];
|
|
@@ -791,6 +828,16 @@ export class PiMonoSession implements ProviderSession {
|
|
|
791
828
|
* task. Checked by `deliverSteering()`.
|
|
792
829
|
*/
|
|
793
830
|
private sessionEnded = false;
|
|
831
|
+
/** Shape of the most recent assistant turn; the last one before idle is the final turn. */
|
|
832
|
+
private lastAssistantTurn: AssistantTurnShape | null = null;
|
|
833
|
+
/** `store-progress` calls with a terminal status that are still running, by tool call id. */
|
|
834
|
+
private pendingTerminalStoreProgress = new Set<string>();
|
|
835
|
+
/** A terminal `store-progress` call (completed or failed) finished without error. */
|
|
836
|
+
private terminalStoreProgressDone = false;
|
|
837
|
+
/** The one-per-session empty-final-turn reprompt has been spent (or skipped for good). */
|
|
838
|
+
private emptyTurnReprompted = false;
|
|
839
|
+
/** `abort()` was called: never prompt a session someone is trying to stop. */
|
|
840
|
+
private abortRequested = false;
|
|
794
841
|
|
|
795
842
|
constructor(
|
|
796
843
|
agentSession: AgentSession,
|
|
@@ -871,6 +918,8 @@ export class PiMonoSession implements ProviderSession {
|
|
|
871
918
|
errorMessage?: string;
|
|
872
919
|
};
|
|
873
920
|
if (endMsg.role === "assistant") {
|
|
921
|
+
const turn = describeAssistantTurn(event.message);
|
|
922
|
+
this.lastAssistantTurn = turn;
|
|
874
923
|
if (endMsg.stopReason === "error") {
|
|
875
924
|
// Candidate terminal failure. May still be cleared by a successful
|
|
876
925
|
// retry (auto_retry_end success / a later good message_end).
|
|
@@ -879,6 +928,16 @@ export class PiMonoSession implements ProviderSession {
|
|
|
879
928
|
}
|
|
880
929
|
// A successful assistant turn means any prior error has recovered.
|
|
881
930
|
this.terminalError = null;
|
|
931
|
+
if (!turn.hasText && !turn.hasToolCall) {
|
|
932
|
+
// Nothing else records these turns: no text and no tool call leaves
|
|
933
|
+
// no trace in session logs. Block types only, never content.
|
|
934
|
+
const tokens =
|
|
935
|
+
turn.outputTokens === undefined ? "" : `, outputTokens=${turn.outputTokens}`;
|
|
936
|
+
this.emit({
|
|
937
|
+
type: "raw_stderr",
|
|
938
|
+
content: `[pi-mono] assistant turn ended with no text and no tool call (stopReason=${turn.stopReason ?? "none"}, content=[${turn.blockTypes.join(",")}]${tokens})\n`,
|
|
939
|
+
});
|
|
940
|
+
}
|
|
882
941
|
}
|
|
883
942
|
// Only assistant text should be printed or used as fallback output.
|
|
884
943
|
const text = extractPiAssistantText(event.message);
|
|
@@ -924,6 +983,14 @@ export class PiMonoSession implements ProviderSession {
|
|
|
924
983
|
break;
|
|
925
984
|
}
|
|
926
985
|
case "tool_execution_start": {
|
|
986
|
+
const status = (event.args as { status?: unknown } | null)?.status;
|
|
987
|
+
if (
|
|
988
|
+
event.toolName.endsWith("store-progress") &&
|
|
989
|
+
typeof status === "string" &&
|
|
990
|
+
TERMINAL_STORE_PROGRESS_STATUSES.has(status)
|
|
991
|
+
) {
|
|
992
|
+
this.pendingTerminalStoreProgress.add(event.toolCallId);
|
|
993
|
+
}
|
|
927
994
|
const model = this.reportedModel();
|
|
928
995
|
this.emit({
|
|
929
996
|
type: "raw_log",
|
|
@@ -948,6 +1015,9 @@ export class PiMonoSession implements ProviderSession {
|
|
|
948
1015
|
break;
|
|
949
1016
|
}
|
|
950
1017
|
case "tool_execution_end":
|
|
1018
|
+
if (this.pendingTerminalStoreProgress.delete(event.toolCallId) && !event.isError) {
|
|
1019
|
+
this.terminalStoreProgressDone = true;
|
|
1020
|
+
}
|
|
951
1021
|
this.emit({
|
|
952
1022
|
type: "raw_log",
|
|
953
1023
|
content: JSON.stringify({
|
|
@@ -998,6 +1068,8 @@ export class PiMonoSession implements ProviderSession {
|
|
|
998
1068
|
// Wait for the agent to finish (poll until not streaming)
|
|
999
1069
|
await this.waitForIdle();
|
|
1000
1070
|
|
|
1071
|
+
await this.repromptAfterEmptyFinalTurn();
|
|
1072
|
+
|
|
1001
1073
|
// Gather cost data
|
|
1002
1074
|
const stats = this.agentSession.getSessionStats();
|
|
1003
1075
|
const cost = this.buildCostData(stats);
|
|
@@ -1071,6 +1143,56 @@ export class PiMonoSession implements ProviderSession {
|
|
|
1071
1143
|
}
|
|
1072
1144
|
}
|
|
1073
1145
|
|
|
1146
|
+
/**
|
|
1147
|
+
* Some models end a session on an assistant turn with no text block and no
|
|
1148
|
+
* tool call (thinking only, or empty content). pi treats that as a clean end,
|
|
1149
|
+
* so a task that needed `store-progress` finishes without a result. Send one
|
|
1150
|
+
* reprompt through the normal prompt path, then wait for idle again.
|
|
1151
|
+
*
|
|
1152
|
+
* Skipped when the final turn has text or a tool call, when it errored or was
|
|
1153
|
+
* aborted, when a terminal `store-progress` call already succeeded, and after
|
|
1154
|
+
* the first reprompt (a second empty turn is not retried).
|
|
1155
|
+
*/
|
|
1156
|
+
private async repromptAfterEmptyFinalTurn(): Promise<void> {
|
|
1157
|
+
if (this.emptyTurnReprompted || !this.finalTurnNeedsReprompt()) return;
|
|
1158
|
+
this.emptyTurnReprompted = true;
|
|
1159
|
+
try {
|
|
1160
|
+
const reprompt = await resolveTemplateAsync("task.nudge.empty_final_turn", {});
|
|
1161
|
+
if (reprompt.skipped || !reprompt.text.trim()) return;
|
|
1162
|
+
// Workers render templates over HTTP, so abort() or a late event can land
|
|
1163
|
+
// while the render is pending. Re-check before starting a new model turn.
|
|
1164
|
+
if (!this.finalTurnNeedsReprompt()) return;
|
|
1165
|
+
this.emit({
|
|
1166
|
+
type: "raw_stderr",
|
|
1167
|
+
content: "[pi-mono] final turn had no text and no tool call; sending one reprompt\n",
|
|
1168
|
+
});
|
|
1169
|
+
await this.agentSession.prompt(reprompt.text, { source: "rpc" });
|
|
1170
|
+
await this.waitForIdle();
|
|
1171
|
+
} catch (err) {
|
|
1172
|
+
// The original outcome stands: a failed nudge must not turn a finished
|
|
1173
|
+
// session into a failed one.
|
|
1174
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1175
|
+
this.emit({
|
|
1176
|
+
type: "raw_stderr",
|
|
1177
|
+
content: `[pi-mono] empty-turn reprompt failed: ${message}\n`,
|
|
1178
|
+
});
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
/** True while the session is still entitled to the one empty-turn reprompt. */
|
|
1183
|
+
private finalTurnNeedsReprompt(): boolean {
|
|
1184
|
+
const turn = this.lastAssistantTurn;
|
|
1185
|
+
return !(
|
|
1186
|
+
this.abortRequested ||
|
|
1187
|
+
this.terminalError ||
|
|
1188
|
+
this.terminalStoreProgressDone ||
|
|
1189
|
+
!turn ||
|
|
1190
|
+
turn.hasText ||
|
|
1191
|
+
turn.hasToolCall ||
|
|
1192
|
+
turn.stopReason === "aborted"
|
|
1193
|
+
);
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1074
1196
|
private waitForIdle(): Promise<void> {
|
|
1075
1197
|
return new Promise<void>((resolve) => {
|
|
1076
1198
|
// Check if already idle
|
|
@@ -1127,6 +1249,7 @@ export class PiMonoSession implements ProviderSession {
|
|
|
1127
1249
|
}
|
|
1128
1250
|
|
|
1129
1251
|
async abort(): Promise<void> {
|
|
1252
|
+
this.abortRequested = true;
|
|
1130
1253
|
await this.agentSession.abort();
|
|
1131
1254
|
}
|
|
1132
1255
|
|
|
@@ -305,6 +305,7 @@ export const LEGACY_POLICY = {
|
|
|
305
305
|
"mcp-server.read.secrets": leadOnly,
|
|
306
306
|
"mcp-oauth.authorize.any": anyAuthenticated,
|
|
307
307
|
"kv.write.any": leadOrOwnNamespace,
|
|
308
|
+
"comb.presence": operatorOrUser,
|
|
308
309
|
"page.delete.any": leadOrResourceOwner,
|
|
309
310
|
"app.manage": anyAuthenticated,
|
|
310
311
|
"app.use": anyAuthenticated,
|
package/src/rbac/permissions.ts
CHANGED
|
@@ -237,6 +237,10 @@ export const PERMISSIONS = {
|
|
|
237
237
|
description: "Write another agent's task:agent: KV namespace.",
|
|
238
238
|
namespace: "kv",
|
|
239
239
|
},
|
|
240
|
+
"comb.presence": {
|
|
241
|
+
description: "Use dashboard presence rooms for Comb drives.",
|
|
242
|
+
namespace: "comb",
|
|
243
|
+
},
|
|
240
244
|
"page.delete.any": {
|
|
241
245
|
description: "Delete a page the caller does not own.",
|
|
242
246
|
namespace: "page",
|
package/src/realtime/auth.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { IncomingMessage } from "node:http";
|
|
2
2
|
import { getAgentById, getTaskById } from "../be/db";
|
|
3
3
|
import { getUserGrant } from "../be/rbac-roles";
|
|
4
|
+
import { getCombConfig } from "../comb/config";
|
|
4
5
|
import { mcpOverflowAuthError } from "../kv-overflow";
|
|
5
6
|
import { reservedNamespaceError } from "../kv-reserved-namespaces";
|
|
6
7
|
import { can, isRbacEnabled } from "../rbac";
|
|
@@ -24,6 +25,20 @@ export type ResolvedRoomNamespace = {
|
|
|
24
25
|
source: "page" | "explicit" | "task" | "agent";
|
|
25
26
|
};
|
|
26
27
|
|
|
28
|
+
export type RoomNamespaceOperation =
|
|
29
|
+
| "join"
|
|
30
|
+
| "leave"
|
|
31
|
+
| "update"
|
|
32
|
+
| "change"
|
|
33
|
+
| "reset"
|
|
34
|
+
| "presence"
|
|
35
|
+
| "subscribe"
|
|
36
|
+
| "unsubscribe"
|
|
37
|
+
| "publish";
|
|
38
|
+
|
|
39
|
+
const COMB_PRESENCE_NAMESPACE = /^presence:comb:[A-Za-z0-9_-]{1,64}:[A-Za-z0-9_-]{1,64}$/;
|
|
40
|
+
const COMB_PRESENCE_OPERATIONS = new Set<RoomNamespaceOperation>(["join", "leave", "presence"]);
|
|
41
|
+
|
|
27
42
|
function pageNamespace(pageId: string): string | null {
|
|
28
43
|
try {
|
|
29
44
|
return pageContextKey({ pageId });
|
|
@@ -86,14 +101,61 @@ export function roomRequestInfo(
|
|
|
86
101
|
export async function authorizeRoomNamespace(
|
|
87
102
|
namespace: string,
|
|
88
103
|
info: RoomAuthorizationInfo,
|
|
89
|
-
|
|
104
|
+
access: boolean | RoomNamespaceOperation,
|
|
90
105
|
): Promise<string | null> {
|
|
91
106
|
const overflowError = mcpOverflowAuthError(namespace, info.agentId);
|
|
92
107
|
if (overflowError) return overflowError;
|
|
93
108
|
|
|
109
|
+
if (namespace.startsWith("presence:comb:")) {
|
|
110
|
+
if (!COMB_PRESENCE_NAMESPACE.test(namespace)) {
|
|
111
|
+
return "invalid Comb presence namespace";
|
|
112
|
+
}
|
|
113
|
+
// Presence is for the swarm's shared Comb drive only, and only while Comb is on.
|
|
114
|
+
const comb = getCombConfig();
|
|
115
|
+
if (!comb.enabled) return "Comb is off";
|
|
116
|
+
if (
|
|
117
|
+
!comb.orgId ||
|
|
118
|
+
!comb.driveId ||
|
|
119
|
+
namespace !== `presence:comb:${comb.orgId}:${comb.driveId}`
|
|
120
|
+
) {
|
|
121
|
+
return "Comb presence is only available for the configured Comb drive";
|
|
122
|
+
}
|
|
123
|
+
if (info.pageId || info.agentId || (!info.isOperator && !info.userId)) {
|
|
124
|
+
return "Comb presence requires dashboard authentication";
|
|
125
|
+
}
|
|
126
|
+
if (typeof access !== "string" || !COMB_PRESENCE_OPERATIONS.has(access)) {
|
|
127
|
+
return "Comb presence rooms only allow join, leave, and presence";
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const principal = info.isOperator
|
|
131
|
+
? ({ kind: "operator" } as const)
|
|
132
|
+
: ({ kind: "user", userId: info.userId! } as const);
|
|
133
|
+
if (
|
|
134
|
+
!can({
|
|
135
|
+
principal,
|
|
136
|
+
verb: "comb.presence",
|
|
137
|
+
resource: { kind: "kv-namespace", namespace },
|
|
138
|
+
source: info.callOrigin === "mcp" ? "mcp" : "http",
|
|
139
|
+
}).allow
|
|
140
|
+
) {
|
|
141
|
+
return "Comb presence requires the comb.presence permission";
|
|
142
|
+
}
|
|
143
|
+
if (info.userId && isRbacEnabled()) {
|
|
144
|
+
const grant = await getUserGrant(info.userId);
|
|
145
|
+
if (!grant.grantsAll && !grant.verbs.has("comb.presence")) {
|
|
146
|
+
return "Comb presence requires the comb.presence permission";
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
|
|
94
152
|
const reservedError = reservedNamespaceError(namespace);
|
|
95
153
|
if (reservedError) return reservedError;
|
|
96
154
|
|
|
155
|
+
const write =
|
|
156
|
+
typeof access === "boolean"
|
|
157
|
+
? access
|
|
158
|
+
: ["update", "change", "reset", "presence", "publish"].includes(access);
|
|
97
159
|
if (!write) return null;
|
|
98
160
|
|
|
99
161
|
if (info.userId && !info.isOperator && isRbacEnabled()) {
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { HttpRequestAuth } from "../utils/request-auth-context";
|
|
2
|
+
|
|
3
|
+
export const REALTIME_TICKET_TTL_MS = 60_000;
|
|
4
|
+
export const REALTIME_TICKET_CAPACITY = 10_000;
|
|
5
|
+
|
|
6
|
+
export type RealtimeTicketAuth = Extract<HttpRequestAuth, { kind: "operator" | "user" }>;
|
|
7
|
+
|
|
8
|
+
type StoredTicket = {
|
|
9
|
+
auth: RealtimeTicketAuth;
|
|
10
|
+
expiresAt: number;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
const tickets = new Map<string, StoredTicket>();
|
|
14
|
+
|
|
15
|
+
export function sweepRealtimeTickets(now = Date.now()): number {
|
|
16
|
+
let removed = 0;
|
|
17
|
+
for (const [ticket, entry] of tickets) {
|
|
18
|
+
if (entry.expiresAt > now) continue;
|
|
19
|
+
tickets.delete(ticket);
|
|
20
|
+
removed++;
|
|
21
|
+
}
|
|
22
|
+
return removed;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function issueRealtimeTicket(
|
|
26
|
+
auth: RealtimeTicketAuth,
|
|
27
|
+
now = Date.now(),
|
|
28
|
+
): { ticket: string; expiresAt: number } {
|
|
29
|
+
sweepRealtimeTickets(now);
|
|
30
|
+
while (tickets.size >= REALTIME_TICKET_CAPACITY) {
|
|
31
|
+
const oldest = tickets.keys().next().value;
|
|
32
|
+
if (oldest === undefined) break;
|
|
33
|
+
tickets.delete(oldest);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
let ticket: string;
|
|
37
|
+
do {
|
|
38
|
+
const bytes = crypto.getRandomValues(new Uint8Array(24));
|
|
39
|
+
ticket = Buffer.from(bytes).toString("base64url");
|
|
40
|
+
} while (tickets.has(ticket));
|
|
41
|
+
|
|
42
|
+
const expiresAt = now + REALTIME_TICKET_TTL_MS;
|
|
43
|
+
tickets.set(ticket, { auth, expiresAt });
|
|
44
|
+
return { ticket, expiresAt };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function redeemRealtimeTicket(ticket: string, now = Date.now()): RealtimeTicketAuth | null {
|
|
48
|
+
const entry = tickets.get(ticket);
|
|
49
|
+
if (!entry) return null;
|
|
50
|
+
tickets.delete(ticket);
|
|
51
|
+
return entry.expiresAt > now ? entry.auth : null;
|
|
52
|
+
}
|
|
@@ -7,6 +7,7 @@ import { findUserById } from "../be/users";
|
|
|
7
7
|
import { resolveHttpRequestAuth } from "../http/auth";
|
|
8
8
|
import { getApiKey } from "../utils/api-key";
|
|
9
9
|
import { extractAndVerifyCookie } from "../utils/page-session";
|
|
10
|
+
import type { HttpRequestAuth } from "../utils/request-auth-context";
|
|
10
11
|
import { scrubSecrets } from "../utils/secret-scrubber";
|
|
11
12
|
import { authorizeRoomNamespace, resolveRoomNamespace } from "./auth";
|
|
12
13
|
import { realtimeBus } from "./bus";
|
|
@@ -20,6 +21,7 @@ import {
|
|
|
20
21
|
roomTopic,
|
|
21
22
|
roomView,
|
|
22
23
|
} from "./rooms";
|
|
24
|
+
import { redeemRealtimeTicket } from "./tickets";
|
|
23
25
|
|
|
24
26
|
const nameSchema = z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/);
|
|
25
27
|
const messageSchema = z.object({
|
|
@@ -56,14 +58,47 @@ type Identity = {
|
|
|
56
58
|
isOperator?: boolean;
|
|
57
59
|
};
|
|
58
60
|
type Viewer = { userId: string; name: string; kind: "user" | "guest" | "agent" };
|
|
61
|
+
type AuthenticatedConnection = {
|
|
62
|
+
identity: Identity;
|
|
63
|
+
me: Viewer;
|
|
64
|
+
expiresAt: number | undefined;
|
|
65
|
+
};
|
|
59
66
|
|
|
60
67
|
function header(req: IncomingMessage, name: string): string | undefined {
|
|
61
68
|
const value = req.headers[name];
|
|
62
69
|
return Array.isArray(value) ? value[0] : value;
|
|
63
70
|
}
|
|
64
71
|
|
|
65
|
-
|
|
72
|
+
function identityFromHttpAuth(
|
|
73
|
+
req: IncomingMessage,
|
|
74
|
+
auth: HttpRequestAuth,
|
|
75
|
+
): AuthenticatedConnection {
|
|
76
|
+
const agentId = auth.kind === "operator" ? header(req, "x-agent-id") : undefined;
|
|
77
|
+
const guestId = `guest-${crypto.randomUUID()}`;
|
|
78
|
+
return {
|
|
79
|
+
identity: {
|
|
80
|
+
agentId,
|
|
81
|
+
sourceTaskId: header(req, "x-source-task-id"),
|
|
82
|
+
userId: auth.kind === "user" ? auth.userId : undefined,
|
|
83
|
+
isOperator: auth.kind === "operator",
|
|
84
|
+
} satisfies Identity,
|
|
85
|
+
me: {
|
|
86
|
+
userId: auth.kind === "user" ? auth.userId : (agentId ?? guestId),
|
|
87
|
+
name: auth.kind === "user" ? auth.user.name : (agentId ?? `Guest ${guestId.slice(-6)}`),
|
|
88
|
+
kind: auth.kind === "user" ? "user" : agentId ? "agent" : "guest",
|
|
89
|
+
} as Viewer,
|
|
90
|
+
expiresAt: undefined,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function authenticate(req: IncomingMessage): Promise<AuthenticatedConnection> {
|
|
66
95
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
96
|
+
const ticket = url.searchParams.get("ticket");
|
|
97
|
+
if (ticket) {
|
|
98
|
+
const auth = redeemRealtimeTicket(ticket);
|
|
99
|
+
if (!auth) throw new Error("Authentication required");
|
|
100
|
+
return identityFromHttpAuth(req, auth);
|
|
101
|
+
}
|
|
67
102
|
const pageId = url.searchParams.get("pageId");
|
|
68
103
|
if (pageId) {
|
|
69
104
|
// Browser credentials must never authorize cross-origin socket requests.
|
|
@@ -90,22 +125,7 @@ async function authenticate(req: IncomingMessage) {
|
|
|
90
125
|
}
|
|
91
126
|
const auth = await resolveHttpRequestAuth(req, getApiKey());
|
|
92
127
|
if (!auth) throw new Error("Authentication required");
|
|
93
|
-
|
|
94
|
-
const guestId = `guest-${crypto.randomUUID()}`;
|
|
95
|
-
return {
|
|
96
|
-
identity: {
|
|
97
|
-
agentId,
|
|
98
|
-
sourceTaskId: header(req, "x-source-task-id"),
|
|
99
|
-
userId: auth.kind === "user" ? auth.userId : undefined,
|
|
100
|
-
isOperator: auth.kind === "operator",
|
|
101
|
-
} satisfies Identity,
|
|
102
|
-
me: {
|
|
103
|
-
userId: auth.kind === "user" ? auth.userId : (agentId ?? guestId),
|
|
104
|
-
name: auth.kind === "user" ? auth.user.name : (agentId ?? `Guest ${guestId.slice(-6)}`),
|
|
105
|
-
kind: auth.kind === "user" ? "user" : agentId ? "agent" : "guest",
|
|
106
|
-
} as Viewer,
|
|
107
|
-
expiresAt: undefined,
|
|
108
|
-
};
|
|
128
|
+
return identityFromHttpAuth(req, auth);
|
|
109
129
|
}
|
|
110
130
|
|
|
111
131
|
function channelTopic(namespace: string, name: string): string {
|
|
@@ -116,11 +136,12 @@ export function attachRealtimeTransport(server: Server): () => void {
|
|
|
116
136
|
const wss = new WebSocketServer({ noServer: true, maxPayload: 3 * 1024 * 1024 });
|
|
117
137
|
let pendingUpgrades = 0;
|
|
118
138
|
let closing = false;
|
|
119
|
-
//
|
|
139
|
+
// Authentication precedes upgrade on both direct and proxied paths.
|
|
120
140
|
const onUpgrade = (req: IncomingMessage, socket: import("node:stream").Duplex, head: Buffer) => {
|
|
141
|
+
const path = req.url?.split("?")[0];
|
|
121
142
|
if (
|
|
122
143
|
closing ||
|
|
123
|
-
|
|
144
|
+
(path !== "/@swarm/realtime" && path !== "/api/realtime") ||
|
|
124
145
|
wss.clients.size + pendingUpgrades >= 1000
|
|
125
146
|
) {
|
|
126
147
|
socket.destroy();
|
|
@@ -227,8 +248,10 @@ function connect(ws: WebSocket, auth: Awaited<ReturnType<typeof authenticate>>):
|
|
|
227
248
|
const resolved = await resolveRoomNamespace(msg.namespace, auth.identity);
|
|
228
249
|
if ("error" in resolved) throw new Error(resolved.error);
|
|
229
250
|
const namespace = resolved.namespace;
|
|
230
|
-
|
|
231
|
-
|
|
251
|
+
if (namespace.startsWith("presence:comb:") && msg.name !== "default") {
|
|
252
|
+
throw new Error("Comb presence uses the default room");
|
|
253
|
+
}
|
|
254
|
+
const denied = await authorizeRoomNamespace(namespace, auth.identity, msg.op);
|
|
232
255
|
if (denied) throw new Error(typeof denied === "string" ? denied : "Forbidden");
|
|
233
256
|
if (closed) return;
|
|
234
257
|
const key = roomTopic(namespace, msg.name);
|
|
@@ -261,7 +284,13 @@ function connect(ws: WebSocket, auth: Awaited<ReturnType<typeof authenticate>>):
|
|
|
261
284
|
room = await getRoom(namespace, msg.name, msg.schemaVersion, { create: false });
|
|
262
285
|
} catch (error) {
|
|
263
286
|
if (!(error instanceof Error) || error.message !== "room does not exist") throw error;
|
|
264
|
-
|
|
287
|
+
// Creating a room is a write. Comb presence rooms take only presence
|
|
288
|
+
// operations, so they check creation as a join.
|
|
289
|
+
const creationDenied = await authorizeRoomNamespace(
|
|
290
|
+
namespace,
|
|
291
|
+
auth.identity,
|
|
292
|
+
namespace.startsWith("presence:comb:") ? "join" : true,
|
|
293
|
+
);
|
|
265
294
|
if (creationDenied) throw new Error(creationDenied);
|
|
266
295
|
if (closed) return;
|
|
267
296
|
room = await getRoom(namespace, msg.name, msg.schemaVersion);
|
|
@@ -18,6 +18,7 @@ declare module "swarm-extension" {
|
|
|
18
18
|
| "system"
|
|
19
19
|
| "linear"
|
|
20
20
|
| "jira"
|
|
21
|
+
| "comb"
|
|
21
22
|
| undefined;
|
|
22
23
|
routingReason?:
|
|
23
24
|
| "skill"
|
|
@@ -127,7 +128,8 @@ declare module "swarm-extension" {
|
|
|
127
128
|
| "azure-devops"
|
|
128
129
|
| "system"
|
|
129
130
|
| "linear"
|
|
130
|
-
| "jira"
|
|
131
|
+
| "jira"
|
|
132
|
+
| "comb";
|
|
131
133
|
tags: string[];
|
|
132
134
|
priority: number;
|
|
133
135
|
dependsOn: string[];
|