@rubytech/create-realagent-code 0.1.330 → 0.1.332

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.
Files changed (155) hide show
  1. package/dist/index.js +19 -2
  2. package/package.json +1 -1
  3. package/payload/platform/config/brand.json +1 -0
  4. package/payload/platform/lib/account-enumeration/dist/index.d.ts +33 -0
  5. package/payload/platform/lib/account-enumeration/dist/index.d.ts.map +1 -1
  6. package/payload/platform/lib/account-enumeration/dist/index.js +76 -0
  7. package/payload/platform/lib/account-enumeration/dist/index.js.map +1 -1
  8. package/payload/platform/lib/account-enumeration/src/index.ts +78 -0
  9. package/payload/platform/lib/mcp-spawn-tee/dist/index.d.ts +24 -24
  10. package/payload/platform/lib/mcp-spawn-tee/dist/index.js +109 -75
  11. package/payload/platform/lib/mcp-spawn-tee/dist/index.js.map +1 -1
  12. package/payload/platform/lib/mcp-spawn-tee/src/__tests__/spawn-tee.test.ts +56 -19
  13. package/payload/platform/lib/mcp-spawn-tee/src/index.ts +112 -77
  14. package/payload/platform/neo4j/schema.cypher +58 -4
  15. package/payload/platform/plugins/admin/.claude-plugin/plugin.json +1 -1
  16. package/payload/platform/plugins/admin/PLUGIN.md +13 -1
  17. package/payload/platform/plugins/admin/lib/mcp-spawn-tee/index.js +109 -75
  18. package/payload/platform/plugins/admin/mcp/dist/index.js +102 -0
  19. package/payload/platform/plugins/admin/mcp/dist/index.js.map +1 -1
  20. package/payload/platform/plugins/admin/mcp/dist/tools/__tests__/account-lifecycle.test.d.ts +2 -0
  21. package/payload/platform/plugins/admin/mcp/dist/tools/__tests__/account-lifecycle.test.d.ts.map +1 -0
  22. package/payload/platform/plugins/admin/mcp/dist/tools/__tests__/account-lifecycle.test.js +57 -0
  23. package/payload/platform/plugins/admin/mcp/dist/tools/__tests__/account-lifecycle.test.js.map +1 -0
  24. package/payload/platform/plugins/admin/mcp/dist/tools/account-lifecycle.d.ts +34 -0
  25. package/payload/platform/plugins/admin/mcp/dist/tools/account-lifecycle.d.ts.map +1 -0
  26. package/payload/platform/plugins/admin/mcp/dist/tools/account-lifecycle.js +78 -0
  27. package/payload/platform/plugins/admin/mcp/dist/tools/account-lifecycle.js.map +1 -0
  28. package/payload/platform/plugins/admin/skills/plainly/SKILL.md +7 -0
  29. package/payload/platform/plugins/admin/skills/platform-architecture/SKILL.md +2 -2
  30. package/payload/platform/plugins/aeo/lib/mcp-spawn-tee/index.js +109 -75
  31. package/payload/platform/plugins/browser/lib/mcp-spawn-tee/index.js +109 -75
  32. package/payload/platform/plugins/contacts/lib/mcp-spawn-tee/index.js +109 -75
  33. package/payload/platform/plugins/contacts/mcp/dist/index.js +1 -1
  34. package/payload/platform/plugins/contacts/mcp/dist/index.js.map +1 -1
  35. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/contact-lookup.test.d.ts +2 -0
  36. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/contact-lookup.test.d.ts.map +1 -0
  37. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/contact-lookup.test.js +71 -0
  38. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/contact-lookup.test.js.map +1 -0
  39. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/group-create.test.d.ts +2 -0
  40. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/group-create.test.d.ts.map +1 -0
  41. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/group-create.test.js +112 -0
  42. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/group-create.test.js.map +1 -0
  43. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/group-manage.test.d.ts +2 -0
  44. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/group-manage.test.d.ts.map +1 -0
  45. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/group-manage.test.js +102 -0
  46. package/payload/platform/plugins/contacts/mcp/dist/tools/__tests__/group-manage.test.js.map +1 -0
  47. package/payload/platform/plugins/contacts/mcp/dist/tools/contact-lookup.d.ts +1 -0
  48. package/payload/platform/plugins/contacts/mcp/dist/tools/contact-lookup.d.ts.map +1 -1
  49. package/payload/platform/plugins/contacts/mcp/dist/tools/contact-lookup.js +10 -3
  50. package/payload/platform/plugins/contacts/mcp/dist/tools/contact-lookup.js.map +1 -1
  51. package/payload/platform/plugins/contacts/mcp/dist/tools/group-create.d.ts.map +1 -1
  52. package/payload/platform/plugins/contacts/mcp/dist/tools/group-create.js +7 -2
  53. package/payload/platform/plugins/contacts/mcp/dist/tools/group-create.js.map +1 -1
  54. package/payload/platform/plugins/contacts/mcp/dist/tools/group-manage.d.ts.map +1 -1
  55. package/payload/platform/plugins/contacts/mcp/dist/tools/group-manage.js +5 -4
  56. package/payload/platform/plugins/contacts/mcp/dist/tools/group-manage.js.map +1 -1
  57. package/payload/platform/plugins/contacts/mcp/package.json +4 -2
  58. package/payload/platform/plugins/docs/references/admin-ui.md +1 -1
  59. package/payload/platform/plugins/email/lib/mcp-spawn-tee/index.js +109 -75
  60. package/payload/platform/plugins/memory/.claude-plugin/plugin.json +1 -1
  61. package/payload/platform/plugins/memory/PLUGIN.md +1 -1
  62. package/payload/platform/plugins/memory/lib/mcp-spawn-tee/index.js +109 -75
  63. package/payload/platform/plugins/memory/mcp/dist/index.js +3 -1
  64. package/payload/platform/plugins/memory/mcp/dist/index.js.map +1 -1
  65. package/payload/platform/plugins/memory/mcp/dist/tools/__tests__/memory-lookup-by-name.test.js +39 -0
  66. package/payload/platform/plugins/memory/mcp/dist/tools/__tests__/memory-lookup-by-name.test.js.map +1 -1
  67. package/payload/platform/plugins/memory/mcp/dist/tools/memory-lookup-by-name.d.ts.map +1 -1
  68. package/payload/platform/plugins/memory/mcp/dist/tools/memory-lookup-by-name.js +13 -1
  69. package/payload/platform/plugins/memory/mcp/dist/tools/memory-lookup-by-name.js.map +1 -1
  70. package/payload/platform/plugins/memory/references/schema-estate-agent.md +17 -5
  71. package/payload/platform/plugins/outlook/lib/mcp-spawn-tee/index.js +109 -75
  72. package/payload/platform/plugins/quickbooks/lib/mcp-spawn-tee/index.js +109 -75
  73. package/payload/platform/plugins/replicate/lib/mcp-spawn-tee/index.js +109 -75
  74. package/payload/platform/plugins/scheduling/lib/mcp-spawn-tee/index.js +109 -75
  75. package/payload/platform/plugins/url-get/lib/mcp-spawn-tee/index.js +109 -75
  76. package/payload/platform/plugins/whatsapp/lib/mcp-spawn-tee/index.js +109 -75
  77. package/payload/platform/plugins/work/lib/mcp-spawn-tee/index.js +109 -75
  78. package/payload/platform/plugins/workflows/lib/mcp-spawn-tee/index.js +109 -75
  79. package/payload/platform/scripts/__tests__/provision-role-stamp.test.sh +40 -0
  80. package/payload/platform/scripts/__tests__/sweep-durability.test.sh +103 -0
  81. package/payload/platform/scripts/lib/provision-account-dir.sh +319 -0
  82. package/payload/platform/scripts/lib/resolve-account-dir.sh +79 -132
  83. package/payload/platform/scripts/seed-neo4j.sh +18 -0
  84. package/payload/platform/scripts/setup-account.sh +28 -361
  85. package/payload/platform/services/claude-session-manager/dist/canonical-tool-names.generated.d.ts.map +1 -1
  86. package/payload/platform/services/claude-session-manager/dist/canonical-tool-names.generated.js +4 -0
  87. package/payload/platform/services/claude-session-manager/dist/canonical-tool-names.generated.js.map +1 -1
  88. package/payload/platform/services/claude-session-manager/dist/config.d.ts +18 -0
  89. package/payload/platform/services/claude-session-manager/dist/config.d.ts.map +1 -1
  90. package/payload/platform/services/claude-session-manager/dist/config.js +63 -7
  91. package/payload/platform/services/claude-session-manager/dist/config.js.map +1 -1
  92. package/payload/platform/services/claude-session-manager/dist/http-server.d.ts.map +1 -1
  93. package/payload/platform/services/claude-session-manager/dist/http-server.js +30 -2
  94. package/payload/platform/services/claude-session-manager/dist/http-server.js.map +1 -1
  95. package/payload/platform/services/claude-session-manager/dist/index.js +16 -1
  96. package/payload/platform/services/claude-session-manager/dist/index.js.map +1 -1
  97. package/payload/platform/services/claude-session-manager/dist/rc-daemon.d.ts.map +1 -1
  98. package/payload/platform/services/claude-session-manager/dist/rc-daemon.js +7 -0
  99. package/payload/platform/services/claude-session-manager/dist/rc-daemon.js.map +1 -1
  100. package/payload/platform/services/claude-session-manager/dist/session-sidecar.d.ts +5 -0
  101. package/payload/platform/services/claude-session-manager/dist/session-sidecar.d.ts.map +1 -1
  102. package/payload/platform/services/claude-session-manager/dist/session-sidecar.js +8 -0
  103. package/payload/platform/services/claude-session-manager/dist/session-sidecar.js.map +1 -1
  104. package/payload/platform/services/claude-session-manager/dist/stuck-turn.d.ts +6 -0
  105. package/payload/platform/services/claude-session-manager/dist/stuck-turn.d.ts.map +1 -1
  106. package/payload/platform/services/claude-session-manager/dist/stuck-turn.js +17 -5
  107. package/payload/platform/services/claude-session-manager/dist/stuck-turn.js.map +1 -1
  108. package/payload/platform/services/webchat-channel/dist/instructions.d.ts.map +1 -1
  109. package/payload/platform/services/webchat-channel/dist/instructions.js +25 -1
  110. package/payload/platform/services/webchat-channel/dist/instructions.js.map +1 -1
  111. package/payload/platform/services/webchat-channel/dist/notification.d.ts +17 -0
  112. package/payload/platform/services/webchat-channel/dist/notification.d.ts.map +1 -1
  113. package/payload/platform/services/webchat-channel/dist/notification.js +14 -0
  114. package/payload/platform/services/webchat-channel/dist/notification.js.map +1 -1
  115. package/payload/platform/services/webchat-channel/dist/server.d.ts.map +1 -1
  116. package/payload/platform/services/webchat-channel/dist/server.js +66 -2
  117. package/payload/platform/services/webchat-channel/dist/server.js.map +1 -1
  118. package/payload/platform/services/webchat-channel/dist/turn-follow.d.ts +28 -0
  119. package/payload/platform/services/webchat-channel/dist/turn-follow.d.ts.map +1 -0
  120. package/payload/platform/services/webchat-channel/dist/turn-follow.js +188 -0
  121. package/payload/platform/services/webchat-channel/dist/turn-follow.js.map +1 -0
  122. package/payload/platform/services/whatsapp-channel/dist/notification.d.ts.map +1 -1
  123. package/payload/platform/services/whatsapp-channel/dist/notification.js +24 -1
  124. package/payload/platform/services/whatsapp-channel/dist/notification.js.map +1 -1
  125. package/payload/platform/templates/account.json +2 -0
  126. package/payload/premium-plugins/real-agent/agents/listing-curator.md +20 -11
  127. package/payload/server/public/assets/AdminLoginScreens-DexSvtjD.js +1 -0
  128. package/payload/server/public/assets/AdminShell-Bf9tndNg.js +1 -0
  129. package/payload/server/public/assets/{Checkbox-1flpB9H0.js → Checkbox-D58GsKoQ.js} +1 -1
  130. package/payload/server/public/assets/{OperatorConversations-DrPqB9Ym.css → OperatorConversations-CDdp2nVn.css} +1 -1
  131. package/payload/server/public/assets/OperatorConversations-RmqANYz8.js +9 -0
  132. package/payload/server/public/assets/{admin-BWJTvagN.js → admin-CH5Vkkt4.js} +1 -1
  133. package/payload/server/public/assets/{browser-XM5e-fn1.js → browser-BwDtzSlr.js} +1 -1
  134. package/payload/server/public/assets/chat-3GY0LmYH.js +1 -0
  135. package/payload/server/public/assets/data-CttrzhfL.js +1 -0
  136. package/payload/server/public/assets/{graph-CIIz9Dmh.js → graph-CZSdF2jv.js} +3 -3
  137. package/payload/server/public/assets/{graph-labels-BRKvhE0e.js → graph-labels-Bi0fu8Ns.js} +1 -1
  138. package/payload/server/public/assets/operator-BEivxmRy.js +1 -0
  139. package/payload/server/public/assets/page-DUvT07SB.js +30 -0
  140. package/payload/server/public/assets/{public-BPlZnopr.js → public-B3eIlVbd.js} +1 -1
  141. package/payload/server/public/browser.html +4 -4
  142. package/payload/server/public/chat.html +5 -5
  143. package/payload/server/public/data.html +4 -4
  144. package/payload/server/public/graph.html +6 -6
  145. package/payload/server/public/index.html +6 -6
  146. package/payload/server/public/operator.html +7 -7
  147. package/payload/server/public/public.html +5 -5
  148. package/payload/server/server.js +605 -435
  149. package/payload/server/public/assets/AdminLoginScreens-BnuaXvxN.js +0 -1
  150. package/payload/server/public/assets/AdminShell-Br0DJQNu.js +0 -1
  151. package/payload/server/public/assets/OperatorConversations-C8sITz2_.js +0 -9
  152. package/payload/server/public/assets/chat-COFMxaoC.js +0 -1
  153. package/payload/server/public/assets/data-BHtJozT2.js +0 -1
  154. package/payload/server/public/assets/operator-9hbxrXKm.js +0 -1
  155. package/payload/server/public/assets/page-CXkBfOhG.js +0 -30
@@ -12,12 +12,13 @@
12
12
  // unit-tested pure helpers in ./notification. Mirrors
13
13
  // whatsapp-channel/server.ts minus the outbound transport (no Baileys, no
14
14
  // reply-document) and minus the Task 753 reframe (operator surface).
15
- import { realpathSync } from 'node:fs';
15
+ import { realpathSync, statSync } from 'node:fs';
16
16
  import { pathToFileURL } from 'node:url';
17
17
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
18
18
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
19
19
  import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
20
- import { acceptsKey, composeContent, buildReplyPostBody, buildReceivedPostBody, buildReplyError, redactInternalLeaks, postWithRetry, } from './notification.js';
20
+ import { acceptsKey, composeContent, buildReplyPostBody, buildReceivedPostBody, buildTurnEndPostBody, buildReplyError, redactInternalLeaks, postWithRetry, } from './notification.js';
21
+ import { findJsonlForSessionId, followTurnEnds } from './turn-follow.js';
21
22
  import { buildPermissionRegisterBody, permissionVerdictParams, permissionRequestNotificationSchema, PERMISSION_VERDICT_METHOD, } from './permission.js';
22
23
  import { channelInstructions, replyToolDescription, replyTextDescription, resolveChannelRole } from './instructions.js';
23
24
  function requireEnv(name) {
@@ -28,6 +29,22 @@ function requireEnv(name) {
28
29
  }
29
30
  const KEY = requireEnv('WEBCHAT_CHANNEL_KEY');
30
31
  const GATEWAY_URL = requireEnv('WEBCHAT_CHANNEL_GATEWAY_URL').replace(/\/$/, '');
32
+ // Task 980 — turn-undelivered detection. The session id is carried on the spawn
33
+ // env (webchat-channel-mcp.ts) so the channel server can tail this session's
34
+ // JSONL and reconcile, per turn, whether a reply tool was dispatched. Resolved
35
+ // lazily: a brand-new session has no transcript at startup, so the path is
36
+ // re-resolved on the first inbound. SESSION_ID is empty in unit tests (the
37
+ // module imports without the env), so findJsonlForSessionId is never called and
38
+ // the follower never starts.
39
+ const SESSION_ID = process.env.WEBCHAT_CHANNEL_SESSION_ID ?? '';
40
+ let jsonlPath = SESSION_ID ? findJsonlForSessionId(SESSION_ID) : null;
41
+ // Count inbound this server emitted but whose turn-end the follower has not yet
42
+ // reported, and whether the session-long follower is running. Mirrors the
43
+ // WhatsApp twin: a turn queued mid-turn is covered by the next end_turn the
44
+ // follower reports, and a claude.ai-driven turn (pendingTurns === 0) reports
45
+ // nothing.
46
+ let pendingTurns = 0;
47
+ let followerStarted = false;
31
48
  // Receipt-ack retry budget. 5 attempts × 2000ms = up to ~8s of sleeping,
32
49
  // comfortably inside the gateway's 30s ack window (ACK_THRESHOLD_MS), so a
33
50
  // recovered ack lands before the sweep would emit a false drain-undelivered.
@@ -207,6 +224,18 @@ export async function subscribeInbound() {
207
224
  // Task 772 plain-delivery decision; PUBLIC stays plain (echo-leak).
208
225
  const composed = composeContent(payload, ROLE);
209
226
  console.error(`[webchat:inbound] op=delivered key=${KEY.slice(0, 8)} role=${ROLE} payloadBytes=${composed.payloadBytes}`);
227
+ // Task 980 — JSONL byte offset at turn start, captured before the emit
228
+ // so the follower catches every line this turn produces. Resilient: a
229
+ // missing/odd file yields 0 and the follow bails fast.
230
+ let turnStartOffset = 0;
231
+ if (jsonlPath) {
232
+ try {
233
+ turnStartOffset = statSync(jsonlPath).size;
234
+ }
235
+ catch {
236
+ turnStartOffset = 0;
237
+ }
238
+ }
210
239
  await mcp.notification({
211
240
  method: 'notifications/claude/channel',
212
241
  params: { content: composed.content },
@@ -234,6 +263,41 @@ export async function subscribeInbound() {
234
263
  if (!acked) {
235
264
  console.error(`[webchat:inbound] op=receipt-ack-failed key=${KEY} messageId=${payload.messageId} attempts=${RECEIPT_ACK_ATTEMPTS}`);
236
265
  }
266
+ // Task 980 — count this inbound and ensure the session-long follower is
267
+ // running. Each end_turn the follower reports posts a turn-end decision
268
+ // (and decrements) while an inbound is outstanding. The gateway logs the
269
+ // anomaly; webchat does NOT re-deliver, so only the trimmed end-turn
270
+ // byte length travels — the answer text never leaves this server.
271
+ // Re-resolve the path lazily when it was absent at startup (brand-new
272
+ // session whose JSONL appears on the first turn). The follower is
273
+ // detached so the SSE read loop keeps receiving.
274
+ if (!jsonlPath && SESSION_ID)
275
+ jsonlPath = findJsonlForSessionId(SESSION_ID);
276
+ if (jsonlPath) {
277
+ pendingTurns++;
278
+ if (!followerStarted) {
279
+ followerStarted = true;
280
+ const followPath = jsonlPath;
281
+ const followStart = turnStartOffset;
282
+ void followTurnEnds(followPath, followStart, (outcome) => {
283
+ if (pendingTurns <= 0)
284
+ return;
285
+ pendingTurns--;
286
+ const finalBytes = Buffer.byteLength(outcome.finalText.trim(), 'utf8');
287
+ void fetch(`${GATEWAY_URL}/webchat-channel/turn-end`, {
288
+ method: 'POST',
289
+ headers: { 'content-type': 'application/json' },
290
+ body: JSON.stringify(buildTurnEndPostBody(KEY, SESSION_ID, outcome.replied, finalBytes)),
291
+ }).catch(() => { });
292
+ }).finally(() => {
293
+ // The follower settles only on a stat failure (file unreadable —
294
+ // the session is ending). Clear any outstanding count so a
295
+ // replacement follower started by a later inbound begins clean.
296
+ pendingTurns = 0;
297
+ followerStarted = false;
298
+ });
299
+ }
300
+ }
237
301
  }
238
302
  }
239
303
  console.error('[webchat-channel] inbound stream closed by gateway; reconnecting');
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":";AACA,+EAA+E;AAC/E,0EAA0E;AAC1E,eAAe;AACf,2EAA2E;AAC3E,uDAAuD;AACvD,4EAA4E;AAC5E,wEAAwE;AACxE,8EAA8E;AAC9E,EAAE;AACF,oEAAoE;AACpE,sDAAsD;AACtD,0EAA0E;AAC1E,qEAAqE;AAErE,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AACtC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AACxC,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAA;AAClE,OAAO,EAAE,oBA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,IAAI,CAAC,GAAG,KAAK,aAAa,CAAC,YAAY,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAC7F,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;QACnB,OAAO,CAAC,KAAK,CAAC,4BAA4B,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;QAC7F,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;IACjB,CAAC,CAAC,CAAA;AACJ,CAAC"}
@@ -0,0 +1,28 @@
1
+ export interface TurnOutcome {
2
+ /** A webchat reply tool_use appeared in the turn. */
3
+ replied: boolean;
4
+ /** Text of the end_turn assistant message ('' when none / not yet reached). */
5
+ finalText: string;
6
+ /** The turn reached an assistant end_turn. */
7
+ reachedEndTurn: boolean;
8
+ }
9
+ /** Fold one turn's JSONL line strings into the delivery decision. Pure. */
10
+ export declare function reduceTurnFromLines(lines: string[]): TurnOutcome;
11
+ export type OnTurnEnd = (outcome: TurnOutcome) => void;
12
+ /**
13
+ * Walk `${CLAUDE_CONFIG_DIR}/projects/<slug>/` for `${sessionId}.jsonl` (live
14
+ * and archived). Returns the first match or null. Inlined from
15
+ * whatsapp-channel/jsonl-watch.ts (itself inlined from
16
+ * claude-session-manager/src/jsonl-path.ts) to avoid a cross-package dep.
17
+ */
18
+ export declare function findJsonlForSessionId(sessionId: string, env?: NodeJS.ProcessEnv): string | null;
19
+ /**
20
+ * Tail `jsonlPath` from `startOffset` for the life of the session, invoking
21
+ * `onTurnEnd` once for every assistant end_turn with that turn's outcome. It
22
+ * segments the JSONL at each end_turn so a follow-on turn produced from a
23
+ * mid-turn-queued message is reported too. The process dies with the session,
24
+ * so there is no per-turn timeout; the promise resolves only when the file
25
+ * becomes unreadable. Never rejects. (Mirror of the WhatsApp twin.)
26
+ */
27
+ export declare function followTurnEnds(jsonlPath: string, startOffset: number, onTurnEnd: OnTurnEnd): Promise<void>;
28
+ //# sourceMappingURL=turn-follow.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"turn-follow.d.ts","sourceRoot":"","sources":["../src/turn-follow.ts"],"names":[],"mappings":"AAwBA,MAAM,WAAW,WAAW;IAC1B,qDAAqD;IACrD,OAAO,EAAE,OAAO,CAAA;IAChB,+EAA+E;IAC/E,SAAS,EAAE,MAAM,CAAA;IACjB,8CAA8C;IAC9C,cAAc,EAAE,OAAO,CAAA;CACxB;AAUD,2EAA2E;AAC3E,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,WAAW,CAoChE;AAED,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,EAAE,WAAW,KAAK,IAAI,CAAA;AAkBtD;;;;;GAKG;AACH,wBAAgB,qBAAqB,CACnC,SAAS,EAAE,MAAM,EACjB,GAAG,GAAE,MAAM,CAAC,UAAwB,GACnC,MAAM,GAAG,IAAI,CAmBf;AAED;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAClC,SAAS,EAAE,MAAM,EACjB,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,SAAS,GACnB,OAAO,CAAC,IAAI,CAAC,CAgEf"}
@@ -0,0 +1,188 @@
1
+ // Turn-end detector for the webchat native channel (Task 980). A faithful
2
+ // mirror of whatsapp-channel/turn-follow.ts — `reduceTurnFromLines` folds one
3
+ // turn's JSONL lines into the delivery decision and `followTurnEnds` tails the
4
+ // session JSONL from a byte offset and reports every assistant end_turn (not
5
+ // just the first), so a follow-on turn produced from a mid-turn-queued message
6
+ // is covered too. Pure of the MCP SDK so it unit-tests in isolation.
7
+ //
8
+ // The divergence from the WhatsApp twin: webchat has no fallback delivery and
9
+ // no reply-document tool. The follower exists ONLY to detect the
10
+ // turn-undelivered anomaly — a channel turn that ends with substantive
11
+ // assistant text but never called the reply tool, so the operator (who sees
12
+ // only reply-tool text in the browser reader) receives nothing. The reply text
13
+ // itself is never delivered or re-sent here; the gateway logs the anomaly.
14
+ import { closeSync, existsSync, openSync, readdirSync, readSync, statSync, watch } from 'node:fs';
15
+ import { homedir } from 'node:os';
16
+ import { join } from 'node:path';
17
+ // The reply tool the agent uses to deliver to the webchat browser. Its presence
18
+ // in a turn means the operator received something this turn. Mirrors
19
+ // WEBCHAT_CHANNEL_SERVER_NAME ('webchat-channel') in claude-session-manager's
20
+ // webchat-channel-mcp.ts; kept as a literal here to avoid a cross-package
21
+ // import. Webchat exposes no reply-document tool, so this set has one member.
22
+ const REPLY_TOOL_NAMES = new Set(['mcp__webchat-channel__reply']);
23
+ /** Fold one turn's JSONL line strings into the delivery decision. Pure. */
24
+ export function reduceTurnFromLines(lines) {
25
+ let replied = false;
26
+ let finalText = '';
27
+ let reachedEndTurn = false;
28
+ for (const line of lines) {
29
+ if (!line)
30
+ continue;
31
+ let ev;
32
+ try {
33
+ ev = JSON.parse(line);
34
+ }
35
+ catch {
36
+ continue;
37
+ }
38
+ if (ev.type !== 'assistant')
39
+ continue;
40
+ const msg = ev.message;
41
+ const isEnd = msg?.stop_reason === 'end_turn';
42
+ if (!msg || !Array.isArray(msg.content)) {
43
+ if (isEnd) {
44
+ reachedEndTurn = true;
45
+ finalText = '';
46
+ }
47
+ continue;
48
+ }
49
+ let endText = '';
50
+ for (const block of msg.content) {
51
+ if (block?.type === 'tool_use' && typeof block.name === 'string' && REPLY_TOOL_NAMES.has(block.name)) {
52
+ replied = true;
53
+ }
54
+ else if (block?.type === 'text' && typeof block.text === 'string' && isEnd) {
55
+ endText += block.text;
56
+ }
57
+ }
58
+ if (isEnd) {
59
+ reachedEndTurn = true;
60
+ finalText = endText;
61
+ }
62
+ }
63
+ return { replied, finalText, reachedEndTurn };
64
+ }
65
+ /** True iff `line` is an assistant message with stop_reason 'end_turn'. */
66
+ function isAssistantEndTurn(line) {
67
+ if (!line)
68
+ return false;
69
+ let ev;
70
+ try {
71
+ ev = JSON.parse(line);
72
+ }
73
+ catch {
74
+ return false;
75
+ }
76
+ return ev.type === 'assistant' && ev.message?.stop_reason === 'end_turn';
77
+ }
78
+ function claudeConfigRoot(env) {
79
+ return env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude');
80
+ }
81
+ /**
82
+ * Walk `${CLAUDE_CONFIG_DIR}/projects/<slug>/` for `${sessionId}.jsonl` (live
83
+ * and archived). Returns the first match or null. Inlined from
84
+ * whatsapp-channel/jsonl-watch.ts (itself inlined from
85
+ * claude-session-manager/src/jsonl-path.ts) to avoid a cross-package dep.
86
+ */
87
+ export function findJsonlForSessionId(sessionId, env = process.env) {
88
+ const projectsRoot = join(claudeConfigRoot(env), 'projects');
89
+ if (!existsSync(projectsRoot))
90
+ return null;
91
+ let slugs;
92
+ try {
93
+ slugs = readdirSync(projectsRoot, { withFileTypes: true })
94
+ .filter((d) => d.isDirectory())
95
+ .map((d) => d.name);
96
+ }
97
+ catch {
98
+ return null;
99
+ }
100
+ const basename = `${sessionId}.jsonl`;
101
+ for (const slug of slugs) {
102
+ const live = join(projectsRoot, slug, basename);
103
+ if (existsSync(live))
104
+ return live;
105
+ const archived = join(projectsRoot, slug, 'archive', basename);
106
+ if (existsSync(archived))
107
+ return archived;
108
+ }
109
+ return null;
110
+ }
111
+ /**
112
+ * Tail `jsonlPath` from `startOffset` for the life of the session, invoking
113
+ * `onTurnEnd` once for every assistant end_turn with that turn's outcome. It
114
+ * segments the JSONL at each end_turn so a follow-on turn produced from a
115
+ * mid-turn-queued message is reported too. The process dies with the session,
116
+ * so there is no per-turn timeout; the promise resolves only when the file
117
+ * becomes unreadable. Never rejects. (Mirror of the WhatsApp twin.)
118
+ */
119
+ export async function followTurnEnds(jsonlPath, startOffset, onTurnEnd) {
120
+ let baseSize;
121
+ try {
122
+ baseSize = statSync(jsonlPath).size;
123
+ }
124
+ catch {
125
+ return;
126
+ }
127
+ return new Promise((resolve) => {
128
+ let offset = Math.min(startOffset, baseSize);
129
+ let carry = '';
130
+ let segment = [];
131
+ let settled = false;
132
+ const settle = () => {
133
+ if (settled)
134
+ return;
135
+ settled = true;
136
+ watcher.close();
137
+ clearInterval(poll);
138
+ resolve();
139
+ };
140
+ // Poll as well as watch: fs.watch misses appends on some platforms (notably
141
+ // macOS), so a light poll guarantees growth is seen within the interval.
142
+ const poll = setInterval(() => drain(), 200);
143
+ const drain = () => {
144
+ let end;
145
+ try {
146
+ end = statSync(jsonlPath).size;
147
+ }
148
+ catch {
149
+ settle();
150
+ return;
151
+ }
152
+ if (end <= offset)
153
+ return;
154
+ let buf;
155
+ try {
156
+ const fd = openSync(jsonlPath, 'r');
157
+ try {
158
+ buf = Buffer.alloc(end - offset);
159
+ readSync(fd, buf, 0, buf.length, offset);
160
+ }
161
+ finally {
162
+ closeSync(fd);
163
+ }
164
+ }
165
+ catch {
166
+ settle();
167
+ return;
168
+ }
169
+ offset = end;
170
+ carry += buf.toString('utf8');
171
+ let nl = carry.indexOf('\n');
172
+ while (nl !== -1) {
173
+ const line = carry.slice(0, nl);
174
+ carry = carry.slice(nl + 1);
175
+ nl = carry.indexOf('\n');
176
+ segment.push(line);
177
+ if (isAssistantEndTurn(line)) {
178
+ onTurnEnd(reduceTurnFromLines(segment));
179
+ segment = [];
180
+ }
181
+ }
182
+ };
183
+ const watcher = watch(jsonlPath, { persistent: false }, () => drain());
184
+ watcher.on('error', () => settle());
185
+ drain(); // catch lines already present between startOffset and now
186
+ });
187
+ }
188
+ //# sourceMappingURL=turn-follow.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"turn-follow.js","sourceRoot":"","sources":["../src/turn-follow.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,8EAA8E;AAC9E,+EAA+E;AAC/E,6EAA6E;AAC7E,+EAA+E;AAC/E,qEAAqE;AACrE,EAAE;AACF,8EAA8E;AAC9E,iEAAiE;AACjE,uEAAuE;AACvE,4EAA4E;AAC5E,+EAA+E;AAC/E,2EAA2E;AAC3E,OAAO,EAAE,S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M,CAAA;CAAE,EAOhE,CAAA;AAED,MAAM,WAAW,SAAS;IACxB,OAAO,EAAE,MAAM,CAAA;IACf,KAAK,EAAE,MAAM,CAAA;CACd;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,SAAS,EAAE,CAAA;CAAE,CAU5F"}
@@ -54,13 +54,36 @@ export const REFRAME_INSTRUCTION = 'Choose the installed specialist that owns th
54
54
  'Call the reply tool right away to acknowledge you are on it, ' +
55
55
  'send a brief progress note with the reply tool before each long step, and call the reply tool again with the result — ' +
56
56
  'never stay silent until the end. ' +
57
+ // Task 980 — the channel/visibility model. A channel turn can end with its
58
+ // substantive answer written as plain assistant text and no reply-tool call;
59
+ // the operator never receives it. The bare cadence clause above read as
60
+ // progress-note etiquette, so this clause states the mechanism and consequence
61
+ // outright: the operator sees ONLY reply-tool text, so a turn-final plain text
62
+ // block delivers nothing. IDENTICAL to the webchat twin's clause in
63
+ // ADMIN_REFRAME_INSTRUCTION (recipient-neutral so the literal matches),
64
+ // drift-guarded by a test in each service.
65
+ 'Remember you are answering over a channel: the person you are replying to is not watching this session ' +
66
+ 'and sees only the text you send with the reply tool. ' +
67
+ 'Anything you write as an ordinary assistant message, without calling the reply tool, is invisible to them. ' +
68
+ 'So a turn that answers them is finished only once you have called the reply tool with the full answer; ' +
69
+ 'a turn that ends without a reply tool call delivers nothing, no matter what you wrote. ' +
57
70
  // Task 919 — the bridge forwards a SendUserFile call to this conversation as a
58
71
  // real attachment. Steer the agent to deliver the file, not describe it. This
59
72
  // clause is identical in the webchat twin (ADMIN_REFRAME_INSTRUCTION) and
60
73
  // drift-guarded by a test in each service.
61
74
  'When you have produced a file to deliver, deliver it by calling SendUserFile with its path — ' +
62
75
  'the platform forwards it to this conversation as an attachment; ' +
63
- 'a reply that only names or describes the file is not delivery.';
76
+ 'a reply that only names or describes the file is not delivery. ' +
77
+ // Task 982 — plain English on every operator-facing reply, not only on explicit
78
+ // "explain in plain English" requests. The plainly skill is installed but
79
+ // otherwise triggers only on that explicit ask, so ordinary replies carry the
80
+ // AI tells it already catalogues. This clause points the agent at the skill for
81
+ // every reply form. IDENTICAL to the webchat twin's clause in
82
+ // ADMIN_REFRAME_INSTRUCTION (recipient-neutral so the literal matches),
83
+ // drift-guarded by a test in each service.
84
+ 'Write every reply you send (acknowledgement, progress note, answer, or deliverable summary) ' +
85
+ 'in plain English, in the spoken register and free of the AI tells the plainly skill catalogues; ' +
86
+ 'load that skill for the full rules.';
64
87
  /**
65
88
  * Shape an inbound WhatsApp payload as a Claude Code channel notification.
66
89
  *
@@ -1 +1 @@
1
- {"version":3,"file":"notification.js","sourceRoot":"","sources":["../src/notification.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,yEAAyE;AACzE,yEAAyE;AAsBzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAC9B,8FAA8F;IAC9F,8GAA8G;IAC9G,iFAAiF;IACjF,0EAA0E;IAC1E,gDAAgD;IAChD,sGAAsG;IACtG,iHAAiH;IACjH,iDAAiD;IACjD,qGAAqG;IACrG,mHAAmH;IACnH,qBAAqB;IACrB,+DAA+D;IAC/D,wHAAwH;IACxH,mCAAmC;IACnC,+EAA+E;IAC/E,8EAA8E;IAC9E,0EAA0E;IAC1E,2CAA2C;IAC3C,+FAA+F;IAC/F,kEAAkE;IAClE,gEAAgE,CAAA;AAiBlE;;;;;;;;;;GAUG;AACH,MAAM,UAAU,wBAAwB,CAAC,CAAiB;IACxD,OAAO;QACL,MAAM,EAAE,8BAAuC;QAC/C,MAAM,EAAE;YACN,OAAO,EAAE,mBAAmB,CAAC,CAAC,CAAC,CAAC,OAAO;SACxC;KACF,CAAA;AACH,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,cAAc,CAAC,CAAiB;IACvC,MAAM,QAAQ,GAAG,CAAC,CAAC,CA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B,CAAC,IAAY;IAC9C,MAAM,UAAU,GAAgB,EAAE,CAAA;IAClC,IAAI,KAAK,GAAG,IAAI,CAAA;IAChB,KAAK,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,IAAI,sBAAsB,EAAE,CAAC;QAClD,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,EAAE;YAC9B,UAAU,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAA;YAC5C,OAAO,YAAY,CAAA;QACrB,CAAC,CAAC,CAAA;IACJ,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,CAAA;AAC9B,CAAC"}
@@ -1,5 +1,7 @@
1
1
  {
2
2
  "accountId": "",
3
+ "role": "",
4
+ "managedService": false,
3
5
  "tier": "",
4
6
  "adminModel": "claude-opus-4-8[1m]",
5
7
  "publicModel": "claude-haiku-4-5",
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: listing-curator
3
- description: "Property listing ingestion. Maps any property-shaped input — a Loop CRM record, a published zip-site directory, or a manual operator dump — to one typed :Listing node that the public agent's memory-search can return as a renderable property card. Delegate when a property listing needs to enter the graph, when an existing Listing's status drifts (for-sale → under-offer → sold), or when a hosted property site has been published and the graph has no record of it yet."
4
- summary: "Your listing curator — maps property inputs to typed :Listing nodes that visitor-facing chat can render."
3
+ description: "Property listing ingestion. Maps any property-shaped input — a Loop CRM record, a published zip-site directory, or a manual operator dump — to an obligatory :Property hub with its child :Listing node that the public agent's memory-search can return as a renderable property card. Delegate when a property listing needs to enter the graph, when an existing Listing's status drifts (for-sale → under-offer → sold), or when a hosted property site has been published and the graph has no record of it yet."
4
+ summary: "Your listing curator — maps property inputs to a :Property hub and its child :Listing nodes that visitor-facing chat can render."
5
5
  model: claude-sonnet-4-6
6
6
  tools: Read, Glob, Bash, mcp__plugin_memory_memory__memory-search, mcp__plugin_memory_memory__memory-write, mcp__plugin_memory_memory__memory-update, mcp__plugin_real-agent-loop_real-agent-loop__loop-property-search, mcp__plugin_real-agent-loop_real-agent-loop__loop-property-detail, mcp__plugin_real-agent-loop_real-agent-loop__loop-property-listed, mcp__plugin_real-agent-loop_real-agent-loop__loop-property-sold, mcp__plugin_real-agent-loop_real-agent-loop__loop-key-list, mcp__plugin_real-agent-loop_real-agent-loop__loop-team-info
7
7
  ---
@@ -12,15 +12,22 @@ tools: Read, Glob, Bash, mcp__plugin_memory_memory__memory-search, mcp__plugin_m
12
12
 
13
13
  Never run uncommanded git writes. `git init`, `git commit`, `git add`, `git stash`, `git reset`, `git checkout`, and branch mutations are forbidden unless the operator named the action in this turn. If a harness precondition demands a git state you don't have, stop and report — never improvise a repo or commit.
14
14
 
15
- You are the listing curator. You own one outcome: any property-shaped input that crosses the realagent boundary leaves the graph as a `:Listing` node carrying the renderable contract from `schema-estate-agent.md`. Generic ingestion specialists (`database-operator`) and hosting flows are not allowed to mint property data — that work routes here so the doctrine is enforced in one place.
15
+ You are the listing curator. You own one outcome: any property-shaped input that crosses the realagent boundary leaves the graph as an obligatory `:Property` hub with its `:Listing` child, both carrying the contract from `schema-estate-agent.md`. Generic ingestion specialists (`database-operator`) and hosting flows are not allowed to mint property data — that work routes here so the doctrine is enforced in one place.
16
16
 
17
- You receive a brief from the admin agent. You read the source, map it field-by-field, and write the Listing. You return the new `:Listing`'s `slug` and the action you took (`create` / `update` / `no-op`).
17
+ You receive a brief from the admin agent. You read the source, map it field-by-field, and write the Property and the Listing. You return the new `:Listing`'s `slug` and the action you took (`create` / `update` / `no-op`).
18
18
 
19
19
  ## Outcome contract
20
20
 
21
- For every property-shaped input the curator returns one `:Listing` node satisfying `schema-estate-agent.md`'s required-property set, idempotent on `(accountId, sourceSystem, sourceId)`. The Listing always carries the parent edge `(:Listing)-[:LISTED_BY]->(:Organization {brandSlug})` naming the estate agency; when a structural `:Property` node is known, additionally `(:Listing)-[:FOR_PROPERTY]->(:Property)`.
21
+ For every property-shaped input the curator returns one `:Property` hub plus one `:Listing` child satisfying `schema-estate-agent.md`'s required-property set. The Property is keyed `(accountId, slug)` on the address-normalised slug; the Listing is keyed `(accountId, sourceSystem, sourceId)`.
22
22
 
23
- `:LocalBusiness` is the per-account installer-seeded singleton (Real Agent itself) and the platform refuses non-system writes to it. The estate agency that listed the property is a third-party business and lives as `:Organization` keyed by `brandSlug`. The curator MERGEs the brand `:Organization` before linking the Listing — see "Brand resolution" below.
23
+ Write order is Property first, then Listing:
24
+
25
+ 1. **MERGE the `:Property`** on `(accountId, slug)`, where `slug` is the address-normalised slug. Set `address` always; set `propertyType` / `tenure` / `epcRating` / `features` only when the source carries them (Property is created address-only when it does not). Attach the mandatory parent edge `(:Property)-[:LISTED_BY]->(:Organization {brandSlug})` naming the estate agency.
26
+ 2. **MERGE the `:Listing`** on `(accountId, sourceSystem, sourceId)` and attach `(:Property)-[:HAS_LISTING]->(:Listing)` (an incoming edge on the new Listing, which satisfies the ≥1-adjacency gate).
27
+
28
+ The agency edge lives on the `:Property`, not the `:Listing`. There is no `(:Listing)-[:LISTED_BY]->` and no `(:Listing)-[:FOR_PROPERTY]->` — both are retired by the Property-hub inversion. A `:Listing` is never written without its parent `:Property`.
29
+
30
+ `:LocalBusiness` is the per-account installer-seeded singleton (Real Agent itself) and the platform refuses non-system writes to it. The estate agency that listed the property is a third-party business and lives as `:Organization` keyed by `brandSlug`. The curator MERGEs the brand `:Organization` before linking the Property — see "Brand resolution" below.
24
31
 
25
32
  Three legal action outcomes:
26
33
 
@@ -28,7 +35,7 @@ Three legal action outcomes:
28
35
  - **`update`** — a Listing existed; its mutable fields were refreshed (status, price, blurb, images, lastVerifiedAt). The `slug`, `sourceSystem`, and `sourceId` are immutable on update.
29
36
  - **`no-op`** — the source record could not be mapped to a complete Listing (see "Source rejection" below). No write occurred. The brief is returned to the admin agent with an explanation.
30
37
 
31
- Anything else — emitting a `:KnowledgeDocument` instead of a `:Listing`, leaving renderable fields null on a `for-sale` listing, creating a second Listing for a re-ingested source record — is a defect.
38
+ Anything else — emitting a `:KnowledgeDocument` instead of a `:Listing`, writing a `:Listing` with no parent `:Property`, leaving renderable fields null on a `for-sale` listing, creating a second Listing for a re-ingested source record, or minting a duplicate `:Property` for an address that already has one — is a defect.
32
39
 
33
40
  ## Source mapping
34
41
 
@@ -90,7 +97,7 @@ The brand `:Organization` parent is resolved from the `<brand>-logo-*.png` filen
90
97
  - zero → emit `no-op` with `reason=brand-unresolved` and return to the admin agent
91
98
  - more than one → emit `no-op` with `reason=brand-ambiguous brands=<comma-separated>` and return to the admin agent
92
99
 
93
- The resolved brand slug is the natural key for `MERGE (o:Organization {accountId, brandSlug})`. Do not invent the brand from the slug, the address, or the property description — only the logo filename counts.
100
+ The resolved brand slug is the natural key for `MERGE (o:Organization {accountId, brandSlug})`, which the curator attaches to the `:Property` via `(:Property)-[:LISTED_BY]->(o)`. Do not invent the brand from the slug, the address, or the property description — only the logo filename counts.
94
101
 
95
102
  #### pageUrl and image URLs
96
103
 
@@ -149,7 +156,7 @@ Write a `no-op` (no Listing produced; admin agent informed) when:
149
156
 
150
157
  - The source has no FACTS block AND no parseable address — there is no `slug` to derive and no `displayName`. The source is metadata about a property the curator hasn't yet been given.
151
158
  - The source declares `status: "off-market"` AND no `pageUrl` is known. These records describe stock not visible to visitors; they belong as `:KnowledgeDocument`-style notes on the linked Property, not as Listings. The admin agent is told to route to the database-operator if the operator wants the note retained.
152
- - The zip-site brand cannot be resolved from `<accountDir>/sites/<slug>/images/*-logo-*.png` — either zero brand logos present (`reason=brand-unresolved`) or more than one distinct brand prefix present (`reason=brand-ambiguous brands=<comma-separated>`). Without a brand the `LISTED_BY -> :Organization` parent cannot be written, and the curator must not invent a brand from the slug or address.
159
+ - The zip-site brand cannot be resolved from `<accountDir>/sites/<slug>/images/*-logo-*.png` — either zero brand logos present (`reason=brand-unresolved`) or more than one distinct brand prefix present (`reason=brand-ambiguous brands=<comma-separated>`). Without a brand the `(:Property)-[:LISTED_BY]->(:Organization)` parent edge cannot be written, so neither the Property hub nor its Listing can be created, and the curator must not invent a brand from the slug or address.
153
160
  - The source's `accountId` cannot be resolved from the session env. Listings without an `accountId` cannot be written under the per-account write gate.
154
161
 
155
162
  `no-op` is loud — the curator returns a one-sentence explanation of which field was missing. Silent skips are defects.
@@ -223,7 +230,7 @@ The migration cypher is run once via SSH against the Pi as a manual backfill ste
223
230
  One structured log line per write, emitted by the curator before returning to the admin agent:
224
231
 
225
232
  ```
226
- [listing-curator] event=property-curated slug=<slug> sourceSystem=<system> sourceId=<id> action=<create|update|no-op> parentLabel=<Organization|—> parentBrandSlug=<brand|—> pageUrl=<url|—> fieldsFilled=<comma-separated-list> fieldsMissing=<comma-separated-list> scope=<scope> imagesWritten=<N> imagesTagged=<M> imagesFailed=<F> imagesFromBrochure=<S> socialTilesRef=<T> brochureRef=<0|1>
233
+ [listing-curator] event=property-curated slug=<slug> sourceSystem=<system> sourceId=<id> action=<create|update|no-op> property=<addressSlug> propertyCreated=<0|1> listingLinked=<0|1> agencyEdge=<0|1> parentLabel=<Organization|—> parentBrandSlug=<brand|—> pageUrl=<url|—> fieldsFilled=<comma-separated-list> fieldsMissing=<comma-separated-list> scope=<scope> imagesWritten=<N> imagesTagged=<M> imagesFailed=<F> imagesFromBrochure=<S> socialTilesRef=<T> brochureRef=<0|1>
227
234
  ```
228
235
 
229
236
  For a `no-op` outcome that didn't even reach the write step (brand-unresolved, brand-ambiguous), emit the same line shape with `action=no-op`, `parentLabel=—`, `parentBrandSlug=—`, `imagesWritten=0`, and an additional `reason=` field naming the rejection:
@@ -234,6 +241,8 @@ For a `no-op` outcome that didn't even reach the write step (brand-unresolved, b
234
241
 
235
242
  `fieldsMissing` is the load-bearing signal on writes. Operators reading the log see at a glance which curations landed incomplete (e.g. `epcUrl` missing on a Loop record means the EPC asset wasn't uploaded to Loop yet; `pageUrl` missing on a zip-site Listing means an upstream defect because the curator now composes it itself). Each missing field is a discoverable defect upstream of the curator, not a curator failure. `parentLabel`/`parentBrandSlug` make the brand resolution visible per-curation without a graph query — a `parentBrandSlug=—` on an `action=create` is an invariant violation.
236
243
 
244
+ `property`/`propertyCreated`/`listingLinked`/`agencyEdge` make the Property-hub inversion visible per-curation. `property` is the address slug the `:Property` was keyed on; `propertyCreated=1` means a new hub was minted (`0` = an existing hub was reused for this address); `listingLinked=1` means the `(:Property)-[:HAS_LISTING]->(:Listing)` edge was written; `agencyEdge=1` means the `(:Property)-[:LISTED_BY]->(:Organization)` parent edge is present. On any `action=create`/`update`, `listingLinked=0` or `agencyEdge=0` is an invariant violation — a Listing reached the graph without its obligatory Property parent or the Property without its agency parent.
245
+
237
246
  `socialTilesRef` (`T`) is the number of URLs written to `socialTileUrls`, and `brochureRef` is `1` when `brochureUrl` was set, else `0`. They make the served-tree harvest visible per-curation: `socialTilesRef=0` against a site whose `socials/` subtree is non-empty is the write-failure signature — the tiles are served but the graph has no reference, and the standing reconcile audit will count them in `unreachable` until the curator is re-run. `brochureRef=0` on a site that published a `brochure.html` is the same signature for the brochure.
238
247
 
239
248
  `imagesWritten` is the total `:ImageObject` count for the Listing after the run. `imagesTagged` is the count with non-empty `tags`. `imagesFailed` counts images where the local `Read` or the JSON-validation failed in the Source B vision branch and a placeholder ImageObject was written with empty description and tags. `imagesFromBrochure` (`S`) is the count of ImageObjects populated from the brochure sidecar (Source A); `S = N` means the curator harvested the brochure entirely and ran no per-image vision; `S = 0` with the sidecar absent is the existing Source B fallback (and `imagesFailed` is the meaningful failure counter in that branch); `0 < S < N` with the sidecar present is filename drift between brochure WebP names and published URLs (the per-image `[listing-curator] image-sidecar-unmatched` lines name which ones). A high `imagesFailed / imagesWritten` ratio on zip-site Listings still means images are missing from `<accountDir>/sites/<slug>/images/` — investigate the publish step, not the vision prompt. When `imagesWritten > 20`, the recommender will only see the first 20 in its `related` set (one-hop expand cap) — emit a separate `[listing-curator] image-cap-warning slug=<slug> imageCount=<N>` line so the cap is visible.
@@ -242,5 +251,5 @@ For a `no-op` outcome that didn't even reach the write step (brand-unresolved, b
242
251
 
243
252
  - Producing the visitor-facing markdown card from a `:Listing`. That's the public agent's job (a separate skill, blocked on this curator's existence; see `.tasks/`).
244
253
  - Inferring missing market-data fields (sold-price comps, demand) — that's the `property-data` MCP, not curator.
245
- - Writing Property structural fields when the source only carries listing data Properties are created by the curator only when the source actually provides `tenure`, `epcRating`, etc.; otherwise the Listing stands on its own with the `LISTED_BY` parent edge.
254
+ - Inferring Property structural fields the source does not carry. The `:Property` hub is always created (address-only is valid), but `propertyType` / `tenure` / `epcRating` / `features` are written only when the source actually provides them the curator never guesses them. A later curation run tops them up when richer source data arrives.
246
255
  - An operator-built `tmp/site-listing-manifest.json` or any other pre-resolved JSON of slug → brand → URL mappings. The curator self-resolves brand and `pageUrl` from the on-disk site, by contract — that is the doctrine-enforcement layer. If an admin agent dispatches the curator over a batch, it does so by enumerating directories (`ls <accountDir>/sites/`) and calling the curator once per slug.
@@ -0,0 +1 @@
1
+ import{o as e}from"./chunk-Pqm5yXtL.js";import{H as t,R as n,S as r,b as i,k as a,y as o}from"./OperatorConversations-RmqANYz8.js";import{i as s}from"./admin-types-CJrGd46U.js";import{g as c,u as l}from"./AdminShell-Bf9tndNg.js";import{t as u}from"./Checkbox-D58GsKoQ.js";var d=`admin-landing-redirected`,f=`/graph`;function p(e){return e.variant===`operator`?!1:e.appState===`chat`&&!e.alreadyRedirected}var m=e(t(),1);function h(e=`admin`){let[t,r]=(0,m.useState)(`loading`),[i,a]=(0,m.useState)(``),[o,l]=(0,m.useState)(``),[u,h]=(0,m.useState)(``),[g,_]=(0,m.useState)(!1),[v,y]=(0,m.useState)(!1),[b,x]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!1),[w,T]=(0,m.useState)(!1),[E,D]=(0,m.useState)(null),[O,k]=(0,m.useState)(null),[A,j]=(0,m.useState)(void 0),[M,N]=(0,m.useState)(null),[P,F]=(0,m.useState)(void 0),[I,L]=(0,m.useState)(null),[ee,R]=(0,m.useState)(null),[z,B]=(0,m.useState)([]),[V,H]=(0,m.useState)(!1),[U,W]=(0,m.useState)(void 0),G=(0,m.useRef)(void 0),[K,q]=(0,m.useState)(!1);(0,m.useEffect)(()=>{typeof window>`u`||fetch(`/api/remote-auth/status`).then(e=>e.ok?e.json():null).then(e=>{e?.configured&&q(!0)}).catch(()=>{})},[]);let J=(0,m.useRef)(null),Y=(0,m.useRef)(null);(0,m.useEffect)(()=>{async function e(){let e=null;try{e=sessionStorage.getItem(`maxy-admin-session-key`)}catch{}if(!e)return!1;try{let t=await fetch(`/api/admin/session?session_key=${encodeURIComponent(e)}`);if(t.status===401){try{sessionStorage.removeItem(`maxy-admin-session-key`)}catch{}return!1}if(!t.ok)return!1;let n=await t.json();D(n.session_key),R(n.sessionId??null),j(n.businessName),N(n.role??null),F(n.userName===void 0?null:n.userName),L(n.avatar??null);let i=s(n.thinkingView);return G.current=i,W(i),r(`chat`),!0}catch(e){return console.error(`[admin] session restore failed:`,e),!1}}async function t(n=2){try{let i=await fetch(`/api/health`);if(!i.ok){if(n>0)return await new Promise(e=>setTimeout(e,1500)),t(n-1);console.error(`[admin] health check returned ${i.status} after retries`),r(`set-pin`);return}let a=await i.json();if(!a.pin_configured){r(`set-pin`);return}if(!a.claude_authenticated){r(`connect-claude`);return}if(await e())return;r(`enter-pin`)}catch(e){if(n>0)return await new Promise(e=>setTimeout(e,1500)),t(n-1);console.error(`[admin] health check failed:`,e),r(`set-pin`)}}t()},[]),(0,m.useEffect)(()=>{t===`chat`&&fetch(`/api/admin/claude-info`).then(e=>{if(e.ok)return e.json()}).then(e=>{e&&k(e)}).catch(()=>{})},[t]),(0,m.useEffect)(()=>{if(typeof window>`u`)return;let n=!1;try{n=sessionStorage.getItem(d)===`1`}catch{}if(p({appState:t,alreadyRedirected:n,variant:e})){try{sessionStorage.setItem(d,`1`)}catch{}console.info(`[admin-ui] landing-redirect target=${f}`),window.location.replace(f)}},[t,e]);let X=(0,m.useRef)(null);(0,m.useEffect)(()=>{if(t!==`chat`)return;let e=setInterval(async()=>{try{let e=await fetch(`/api/health`);if(e.ok){let t=await e.json();if(t.auth_status===`dead`||t.auth_status===`missing`){r(`connect-claude`);return}}}catch{}if(E)try{let e=await fetch(`/api/admin/session?session_key=${encodeURIComponent(E)}`);if(e.status!==401)return;let t=(await e.clone().json().catch(()=>null))?.code??`unknown-401`;if(t===`remote-auth-required`){n(`heartbeat`,`/api/admin/session`);return}console.warn(`[admin-auth] outcome=heartbeat-detected-expiry code=${t}`),X.current?.()}catch{}},300*1e3);return()=>clearInterval(e)},[t,E]),(0,m.useEffect)(()=>{t===`connect-claude`&&fetch(`/api/health`).then(e=>e.ok?e.json():null).then(e=>{e?.claude_authenticated&&r(`enter-pin`)}).catch(()=>{})},[t]);async function Z(e,t){y(!0);try{let n=await fetch(`/api/admin/session`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pin:e,...t?{accountId:t}:{}})});if(!n.ok){h((await n.json().catch(()=>({}))).error||`Invalid PIN`);return}let i=await n.json();if(i.accounts&&!i.session_key){console.log(`[admin] account picker shown: userId=${i.userId} accountCount=${i.accounts.length}`),B(i.accounts),r(`account-picker`);return}D(i.session_key),R(i.sessionId??null),j(i.businessName),N(i.role??null),F(i.userName===void 0?null:i.userName),L(i.avatar??null);let o=s(i.thinkingView);if(G.current=o,W(o),t)try{sessionStorage.setItem(`maxy-account-id`,t)}catch{}try{sessionStorage.setItem(`maxy-admin-session-key`,i.session_key)}catch{}a(``),r(`chat`)}catch(e){console.error(`[admin] connection error:`,e),h(`Could not connect.`)}finally{y(!1),H(!1)}}let Q=(0,m.useCallback)(async e=>{if(e.preventDefault(),v)return;h(``);let t=o.trim();if(!t){h(`Please enter your name.`);return}if(i.length<4){h(`PIN must be at least 4 characters.`);return}let n=i;y(!0);try{let e=await fetch(`/api/onboarding/set-pin`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pin:n,name:t})});if(!e.ok){let t=await e.json().catch(()=>({}));if(e.status===409){console.log(`[admin] PIN already configured — re-checking health`);try{let e=await fetch(`/api/health`);if(e.ok){let n=await e.json();n.pin_configured&&n.claude_authenticated?r(`enter-pin`):n.pin_configured?r(`connect-claude`):h(t.error||`Failed to set PIN.`)}else r(`enter-pin`)}catch{r(`enter-pin`)}return}h(t.error||`Failed to set PIN.`);return}let i=await fetch(`/api/health`);if((i.ok?await i.json():null)?.claude_authenticated){await Z(n);return}a(``),r(`connect-claude`)}catch(e){console.error(`[admin] connection error:`,e),h(`Could not connect.`)}finally{y(!1)}},[i,v,o]),te=(0,m.useCallback)(async e=>{e.preventDefault(),h(``),await Z(i)},[i]),ne=(0,m.useCallback)(async()=>{T(!0);try{if(!await c())return console.warn(`[admin-ui] claude-disconnect not verified — credentials may persist; staying put`),!1;D(null),N(null),F(void 0),L(null);try{sessionStorage.removeItem(`maxy-admin-session-key`),sessionStorage.removeItem(`maxy-account-id`),sessionStorage.removeItem(d)}catch{}return r(`connect-claude`),!0}finally{T(!1)}},[]),$=(0,m.useCallback)(()=>{D(null),N(null),F(void 0),L(null);try{sessionStorage.removeItem(`maxy-admin-session-key`),sessionStorage.removeItem(`maxy-account-id`),sessionStorage.removeItem(d)}catch{}a(``),h(``),r(`enter-pin`)},[]);return(0,m.useEffect)(()=>{X.current=$},[$]),{appState:t,setAppState:r,pin:i,setPin:a,operatorName:o,setOperatorName:l,pinError:u,setPinError:h,showPin:g,setShowPin:_,pinLoading:v,authPolling:b,setAuthPolling:x,authLoading:S,setAuthLoading:C,disconnecting:w,cacheKey:E,setCacheKey:D,claudeInfo:O,setClaudeInfo:k,businessName:A,role:M,userName:P,userAvatar:I,sessionId:ee,setSessionId:R,accounts:z,accountPickerLoading:V,expandAll:U,setExpandAll:W,expandAllDefaultRef:G,remoteAuthEnabled:K,pinInputRef:J,setPinFormRef:Y,handleSetPin:Q,handleLogin:te,handleAccountSelect:(0,m.useCallback)(async e=>{H(!0),h(``),await Z(i,e)},[i]),handleDisconnect:ne,handleLogout:$,handleChangePin:(0,m.useCallback)(async()=>{if(!i){h(`Enter your current PIN first.`);return}y(!0),h(``);try{let e=await fetch(`/api/onboarding/set-pin`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({currentPin:i})});if(!e.ok){h((await e.json().catch(()=>({error:`Incorrect PIN.`}))).error||`Incorrect PIN.`);return}a(``),h(``),r(`set-pin`)}catch(e){console.error(`[admin-auth] change pin failed:`,e),h(e instanceof Error?e.message:String(e))}finally{y(!1)}},[i])}}var g=r();function _({inputRef:e,value:t,onChange:n,onComplete:r,showPin:i,autoFocus:a}){let o=(0,m.useRef)([]);function s(e,r){r.key===`Backspace`?(r.preventDefault(),t[e]?n(t.slice(0,e)+t.slice(e+1)):e>0&&(n(t.slice(0,e-1)+t.slice(e)),o.current[e-1]?.focus())):r.key===`ArrowLeft`&&e>0?o.current[e-1]?.focus():r.key===`ArrowRight`&&e<5?o.current[e+1]?.focus():r.key===`Enter`&&(r.preventDefault(),r.currentTarget.form?.requestSubmit())}function c(e,i){let a=i.nativeEvent.data;if(!a||!/^\d$/.test(a))return;let s=t.split(``);for(s[e]=a;s.length<e;)s.push(``);let c=s.join(``).replace(/\D/g,``).slice(0,6);n(c),c.length===6?r?.(c):e<5&&o.current[e+1]?.focus()}function l(e){e.preventDefault();let t=e.clipboardData.getData(`text`).replace(/\D/g,``).slice(0,6);t&&(n(t),t.length===6?r?.(t):o.current[t.length]?.focus())}return(0,g.jsx)(`div`,{className:`pin-field`,children:Array.from({length:6}).map((n,r)=>(0,g.jsx)(`input`,{ref:t=>{o.current[r]=t,r===0&&e&&(e.current=t)},type:`text`,inputMode:`numeric`,className:`pin-box${t[r]?` pin-box-filled`:``}`,value:t[r]?i?t[r]:`•`:``,onKeyDown:e=>s(r,e),onInput:e=>c(r,e),onPaste:l,onFocus:e=>e.target.select(),autoFocus:a&&r===0,autoComplete:`off`,maxLength:1,"aria-label":`PIN digit ${r+1}`},r))})}function v(e){let{pin:t,setPin:n,showPin:r,setShowPin:a,pinLoading:s,pinError:c,pinInputRef:d,setPinFormRef:f,onSubmit:p,operatorName:m,setOperatorName:h}=e;return(0,g.jsx)(`div`,{className:`connect-page`,children:(0,g.jsxs)(`div`,{className:`connect-content`,children:[(0,g.jsx)(`img`,{src:i,alt:o.productName,className:`connect-logo connect-logo--maxy`}),!o.logoContainsName&&(0,g.jsxs)(`h1`,{className:`connect-title`,children:[`Welcome to `,o.productName]}),(0,g.jsxs)(`p`,{className:`connect-subtitle`,children:[`Tell `,o.productName,` who you are, then choose a PIN.`]}),(0,g.jsxs)(`form`,{ref:f,onSubmit:p,className:`connect-pin-form`,children:[(0,g.jsxs)(`div`,{className:`pin-input-row`,children:[(0,g.jsx)(`input`,{type:`text`,className:`connect-name-input`,placeholder:`Your full name`,value:m,onChange:e=>h(e.target.value),autoComplete:`name`,autoFocus:!0,required:!0,"aria-label":`Your full name`}),(0,g.jsx)(`div`,{style:{width:38,flexShrink:0},"aria-hidden":`true`})]}),(0,g.jsxs)(`div`,{className:`pin-input-row`,children:[(0,g.jsx)(_,{inputRef:d,value:t,onChange:n,onComplete:()=>{},showPin:r}),(0,g.jsx)(l,{variant:`send`,type:`submit`,disabled:!t||!m.trim(),loading:s,"aria-label":`Set PIN`,children:(0,g.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,g.jsx)(`line`,{x1:`5`,y1:`12`,x2:`19`,y2:`12`}),(0,g.jsx)(`polyline`,{points:`12 5 19 12 12 19`})]})})]}),(0,g.jsx)(u,{checked:r,onChange:()=>a(e=>!e),label:`Show PIN`})]}),c&&(0,g.jsx)(`p`,{className:`admin-pin-error`,children:c})]})})}function y(e){let{pin:t,setPin:n,showPin:r,setShowPin:a,pinLoading:s,pinError:c,pinInputRef:d,onSubmit:f,onChangePin:p,remoteAuthEnabled:m,onSignOutRemote:h}=e;return(0,g.jsxs)(`div`,{className:`connect-page`,children:[m&&h&&(0,g.jsx)(`button`,{type:`button`,className:`connect-signout`,onClick:h,children:`Sign out`}),(0,g.jsxs)(`div`,{className:`connect-content`,children:[(0,g.jsx)(`img`,{src:i,alt:o.productName,className:`connect-logo connect-logo--maxy`}),!o.logoContainsName&&(0,g.jsx)(`h1`,{className:`connect-title`,children:o.productName}),(0,g.jsxs)(`form`,{onSubmit:f,className:`connect-pin-form`,children:[(0,g.jsxs)(`div`,{className:`pin-input-row`,children:[(0,g.jsx)(_,{inputRef:d,value:t,onChange:n,onComplete:()=>{},showPin:r,autoFocus:!0}),(0,g.jsx)(l,{variant:`send`,type:`submit`,disabled:!t,loading:s,children:(0,g.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,g.jsx)(`line`,{x1:`5`,y1:`12`,x2:`19`,y2:`12`}),(0,g.jsx)(`polyline`,{points:`12 5 19 12 12 19`})]})})]}),(0,g.jsxs)(`div`,{className:`pin-options`,children:[(0,g.jsx)(u,{checked:r,onChange:()=>a(e=>!e),label:`Show PIN`}),(0,g.jsx)(l,{type:`button`,variant:`ghost`,onClick:p,children:`Change PIN`})]})]}),c&&(0,g.jsx)(`p`,{className:`admin-pin-error`,children:c})]})]})}function b(e){let{accounts:t,loading:n,error:r,onSelect:s}=e;return(0,g.jsx)(`div`,{className:`connect-page`,children:(0,g.jsxs)(`div`,{className:`connect-content`,children:[(0,g.jsx)(`img`,{src:i,alt:o.productName,className:`connect-logo connect-logo--maxy`}),!o.logoContainsName&&(0,g.jsx)(`h1`,{className:`connect-title`,children:o.productName}),(0,g.jsx)(`p`,{className:`connect-subtitle`,children:`Select an account`}),(0,g.jsx)(`div`,{className:`account-picker-list`,children:t.map(e=>(0,g.jsxs)(`button`,{className:`account-picker-card`,onClick:()=>s(e.accountId),disabled:n,type:`button`,children:[(0,g.jsx)(`span`,{className:`account-picker-name`,children:e.businessName||e.accountId}),(0,g.jsx)(`span`,{className:`account-picker-role`,children:e.role}),n&&(0,g.jsx)(a,{className:`account-picker-spinner`,size:16})]},e.accountId))}),r&&(0,g.jsx)(`p`,{className:`admin-pin-error`,children:r})]})})}function x(e){let{authPolling:t,setAuthPolling:n,authLoading:r,setAuthLoading:a,pinError:s,setPinError:c,setAppState:u}=e,[d,f]=(0,m.useState)(!1),[p,h]=(0,m.useState)(!1);async function _(){h(!0),c(``);try{let e=await(await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`launch-browser`})})).json();e.launched?f(!0):e.error&&c(e.error)}catch(e){console.error(`[admin] browser launch error:`,e),c(`Could not launch browser.`)}h(!1)}async function v(){a(!0),c(``);try{let e=await(await fetch(`/api/onboarding/claude-auth`,{method:`POST`})).json();if(e.started){n(!0),f(!0),a(!1);for(let e=0;e<120;e++)if(await new Promise(e=>setTimeout(e,2e3)),(await(await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`wait`})})).json()).authenticated){await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`stop`})}),u(`enter-pin`);return}c(`Timed out waiting for sign-in. Try again.`),n(!1)}else e.error&&c(e.error)}catch(e){console.error(`[admin] auth flow error:`,e),c(`Could not start auth flow.`)}a(!1)}async function y(){await fetch(`/api/onboarding/claude-auth`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`stop`})}),n(!1),c(``)}return t||d?(0,g.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,height:`100dvh`,overflow:`auto`},children:[(0,g.jsxs)(`header`,{className:`chat-header`,style:{paddingBottom:`12px`,flexShrink:0,position:`relative`,maxWidth:`680px`,width:`100%`,margin:`0 auto`,padding:`24px 20px 12px`},children:[t?(0,g.jsx)(`button`,{onClick:y,style:{position:`absolute`,top:`12px`,right:`12px`,background:`none`,border:`none`,color:`#999`,fontSize:`13px`,cursor:`pointer`,padding:`4px 8px`},"aria-label":`Cancel`,children:`✕`}):(0,g.jsx)(`button`,{onClick:()=>f(!1),style:{position:`absolute`,top:`12px`,right:`12px`,background:`none`,border:`none`,color:`#999`,fontSize:`13px`,cursor:`pointer`,padding:`4px 8px`},"aria-label":`Close browser`,children:`✕`}),(0,g.jsx)(`img`,{src:`/brand/claude.png`,alt:`Claude`,className:`chat-logo`}),(0,g.jsx)(`h1`,{className:`chat-tagline`,children:`Connect Claude`}),(0,g.jsx)(`p`,{className:`chat-intro`,children:t?`Sign in and authorize in the browser below.`:`Open your email or prepare your accounts, then sign in.`}),!t&&(0,g.jsx)(`div`,{style:{marginTop:`12px`},children:(0,g.jsx)(l,{variant:`primary`,onClick:v,disabled:r,children:r?(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(`span`,{className:`spin`,style:{display:`inline-block`},children:`✱`}),` Connecting…`]}):`Sign in to Claude`})})]}),(0,g.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,gap:`10px`,padding:`0 0 16px`},children:(0,g.jsx)(`iframe`,{src:`/vnc-viewer.html`,style:{flex:1,width:`100%`,minHeight:0,border:`none`,background:`#111`,display:`block`},title:`Claude Sign-in`})}),s&&(0,g.jsx)(`p`,{className:`admin-pin-error`,style:{textAlign:`center`,padding:`0 20px 16px`},children:s})]}):(0,g.jsx)(`div`,{className:`connect-page`,children:(0,g.jsxs)(`div`,{className:`connect-content`,children:[(0,g.jsxs)(`div`,{className:`connect-logos`,children:[(0,g.jsx)(`div`,{className:`connect-logo-wrap`,children:(0,g.jsx)(`img`,{src:`/brand/claude.png`,alt:`Claude`,className:`connect-logo`})}),(0,g.jsx)(`svg`,{className:`connect-arrow`,viewBox:`0 0 48 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,g.jsx)(`path`,{d:`M0 12h44m0 0l-8-8m8 8l-8 8`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})}),(0,g.jsxs)(`div`,{className:`connect-logo-wrap`,children:[(0,g.jsx)(`img`,{src:i,alt:o.productName,className:`connect-logo connect-logo--maxy`}),!o.logoContainsName&&(0,g.jsx)(`span`,{className:`connect-logo-label`,children:o.productName})]})]}),(0,g.jsxs)(`h1`,{className:`connect-title`,children:[`Connect Claude to power `,o.productName]}),(0,g.jsx)(`p`,{className:`connect-subtitle`,children:`Sign in with your Anthropic account to get started.`}),(0,g.jsx)(l,{variant:`primary`,onClick:v,disabled:r,children:r?(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(`span`,{className:`spin`,style:{display:`inline-block`},children:`✱`}),` Connecting…`]}):`Sign in to Claude`}),(0,g.jsx)(`p`,{style:{marginTop:`6px`,fontSize:`11px`,color:`#999`,maxWidth:`300px`,textAlign:`center`,lineHeight:`1.4`},children:`First time? You may need to sign into your email and Anthropic account in the browser before connecting.`}),(0,g.jsx)(`button`,{onClick:_,disabled:p,style:{marginTop:`12px`,background:`none`,border:`none`,color:`var(--color-primary, #666)`,fontSize:`13px`,cursor:`pointer`,textDecoration:`underline`,textUnderlineOffset:`3px`},children:p?`Launching…`:`Open browser first`}),s&&(0,g.jsx)(`p`,{className:`admin-pin-error`,children:s})]})})}function S({auth:e}){return e.appState===`loading`?(0,g.jsx)(`div`,{className:`connect-page`}):e.appState===`set-pin`?(0,g.jsx)(v,{pin:e.pin,setPin:e.setPin,showPin:e.showPin,setShowPin:e.setShowPin,pinLoading:e.pinLoading,pinError:e.pinError,pinInputRef:e.pinInputRef,setPinFormRef:e.setPinFormRef,onSubmit:e.handleSetPin,operatorName:e.operatorName,setOperatorName:e.setOperatorName}):e.appState===`connect-claude`?(0,g.jsx)(x,{authPolling:e.authPolling,setAuthPolling:e.setAuthPolling,authLoading:e.authLoading,setAuthLoading:e.setAuthLoading,pinError:e.pinError,setPinError:e.setPinError,setAppState:e.setAppState}):e.appState===`enter-pin`?(0,g.jsx)(y,{pin:e.pin,setPin:e.setPin,showPin:e.showPin,setShowPin:e.setShowPin,pinLoading:e.pinLoading,pinError:e.pinError,pinInputRef:e.pinInputRef,onSubmit:e.handleLogin,onChangePin:e.handleChangePin,remoteAuthEnabled:e.remoteAuthEnabled,onSignOutRemote:()=>{console.info(`[admin-ui] remote-auth sign-out → /__remote-auth/logout`),window.location.href=`/__remote-auth/logout`}}):e.appState===`account-picker`?(0,g.jsx)(b,{accounts:e.accounts,loading:e.accountPickerLoading,error:e.pinError,onSelect:e.handleAccountSelect}):null}export{h as n,S as t};