synabun 2.4.5 → 2.4.7

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 (108) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +1 -1
  3. package/docs/whatsapp.md +17 -1
  4. package/hooks/claude-code/session-start.mjs +21 -18
  5. package/lib/claude-global-config.js +214 -0
  6. package/lib/client-config-repair.js +17 -3
  7. package/mcp-server/dist/index.d.ts.map +1 -1
  8. package/mcp-server/dist/index.js +6 -1
  9. package/mcp-server/dist/index.js.map +1 -1
  10. package/mcp-server/dist/services/tool-catalog.js +1 -1
  11. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  12. package/mcp-server/dist/tools/agents.d.ts +2 -0
  13. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  14. package/mcp-server/dist/tools/agents.js +11 -5
  15. package/mcp-server/dist/tools/agents.js.map +1 -1
  16. package/mcp-server/dist/tools/skill-tools.d.ts +24 -5
  17. package/mcp-server/dist/tools/skill-tools.d.ts.map +1 -1
  18. package/mcp-server/dist/tools/skill-tools.js +88 -8
  19. package/mcp-server/dist/tools/skill-tools.js.map +1 -1
  20. package/mcp-server/dist/tools/tool-groups.d.ts.map +1 -1
  21. package/mcp-server/dist/tools/tool-groups.js +19 -4
  22. package/mcp-server/dist/tools/tool-groups.js.map +1 -1
  23. package/mcp-server/package-lock.json +2 -2
  24. package/mcp-server/package.json +1 -1
  25. package/mcp-server/src/index.ts +6 -1
  26. package/mcp-server/src/services/tool-catalog.ts +1 -1
  27. package/mcp-server/src/tools/agents.ts +11 -5
  28. package/mcp-server/src/tools/skill-tools.ts +82 -9
  29. package/mcp-server/src/tools/tool-groups.ts +19 -4
  30. package/neural-interface/i18n/en.json +153 -10
  31. package/neural-interface/i18n/pt-BR.json +153 -10
  32. package/neural-interface/lib/antigravity/panel-bridge.js +7 -3
  33. package/neural-interface/lib/assistant-dispatch.js +15 -1
  34. package/neural-interface/lib/assistant-runtime.js +79 -8
  35. package/neural-interface/lib/assistant-user-context.js +7 -3
  36. package/neural-interface/lib/browser-background-tab.js +12 -0
  37. package/neural-interface/lib/browser-guard-cdp.js +2 -1
  38. package/neural-interface/lib/browser-network-guard.js +140 -3
  39. package/neural-interface/lib/browser-own-targets.js +350 -0
  40. package/neural-interface/lib/claude-agent-bridge.js +13 -2
  41. package/neural-interface/lib/codex-thread-history.js +144 -7
  42. package/neural-interface/lib/codex-worker-app-server.js +84 -30
  43. package/neural-interface/lib/db.js +26 -0
  44. package/neural-interface/lib/greeting/sources.js +7 -3
  45. package/neural-interface/lib/jsonl-lines.js +10 -11
  46. package/neural-interface/lib/launch-block-api.js +86 -0
  47. package/neural-interface/lib/line-buffer.js +88 -0
  48. package/neural-interface/lib/loop-stall.js +15 -1
  49. package/neural-interface/lib/memory-list-read.js +105 -0
  50. package/neural-interface/lib/memory-timers.js +4 -1
  51. package/neural-interface/lib/morelogin-launch-recovery.js +506 -0
  52. package/neural-interface/lib/morelogin-profile-failures.js +48 -1
  53. package/neural-interface/lib/morelogin.js +16 -2
  54. package/neural-interface/lib/native-loop-runtime.js +7 -3
  55. package/neural-interface/lib/provider-panel-api-key-auth.js +33 -6
  56. package/neural-interface/lib/skills/api-v2.js +18 -3
  57. package/neural-interface/lib/skills/bundle.js +2 -2
  58. package/neural-interface/lib/skills/deploy.js +169 -34
  59. package/neural-interface/lib/skills/digest.js +57 -3
  60. package/neural-interface/lib/skills/health.js +55 -1
  61. package/neural-interface/lib/skills/known-bridge-digests.json +12 -0
  62. package/neural-interface/lib/skills/runtime-checks.js +7 -4
  63. package/neural-interface/lib/skills/scan-shell.js +56 -7
  64. package/neural-interface/lib/skills/scan.js +13 -12
  65. package/neural-interface/lib/skills/service.js +7 -2
  66. package/neural-interface/lib/skills/telemetry.js +2 -2
  67. package/neural-interface/lib/teams/README.md +12 -5
  68. package/neural-interface/lib/teams/api.js +15 -4
  69. package/neural-interface/lib/teams/index.js +2 -0
  70. package/neural-interface/lib/teams/landing.js +195 -75
  71. package/neural-interface/lib/teams/scheduler.js +31 -32
  72. package/neural-interface/lib/terminal-token-redaction.js +228 -58
  73. package/neural-interface/lib/terminal-tokens.js +18 -0
  74. package/neural-interface/lib/whatsapp/brain.js +21 -0
  75. package/neural-interface/lib/whatsapp/bridge.js +40 -4
  76. package/neural-interface/package-lock.json +2 -2
  77. package/neural-interface/package.json +1 -1
  78. package/neural-interface/public/index.html +117 -37
  79. package/neural-interface/public/shared/agents/studio/ax-api.js +11 -0
  80. package/neural-interface/public/shared/agents/studio/ax-create-view.js +1 -1
  81. package/neural-interface/public/shared/agents/studio/ax-icons.js +1 -0
  82. package/neural-interface/public/shared/agents/studio/ax-library-view.js +3 -2
  83. package/neural-interface/public/shared/agents/studio/ax-main.js +127 -41
  84. package/neural-interface/public/shared/agents/studio/ax-review-view.js +3 -2
  85. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +137 -39
  86. package/neural-interface/public/shared/agents/studio/ax-teams.js +219 -4
  87. package/neural-interface/public/shared/agents/studio/ax-ui.js +31 -0
  88. package/neural-interface/public/shared/agents/studio/ax-views.js +67 -69
  89. package/neural-interface/public/shared/agents/studio/ax-work-answer.js +86 -0
  90. package/neural-interface/public/shared/agents/studio/ax-work-view.js +305 -0
  91. package/neural-interface/public/shared/agents/studio/ax-work.css +74 -0
  92. package/neural-interface/public/shared/agents/studio/ax-work.js +300 -0
  93. package/neural-interface/public/shared/cdx/cdx-deferred.js +90 -0
  94. package/neural-interface/public/shared/cdx/cdx-render.js +18 -7
  95. package/neural-interface/public/shared/cdx/cdx-tabs.js +2 -1
  96. package/neural-interface/public/shared/launch-block-view.js +124 -0
  97. package/neural-interface/public/shared/loading-diagnostic-entry.js +16 -1
  98. package/neural-interface/public/shared/skills/studio/sx-operations-view.js +5 -0
  99. package/neural-interface/public/shared/skills/studio/sx-plan.js +42 -3
  100. package/neural-interface/public/shared/skills/studio/sx-publish-view.js +20 -4
  101. package/neural-interface/public/shared/styles.css +17 -0
  102. package/neural-interface/public/shared/ui-launch-block-notice.js +155 -0
  103. package/neural-interface/public/shared/ui-navbar.js +11 -0
  104. package/neural-interface/public/shared/ui-sync.js +2 -0
  105. package/neural-interface/server.js +745 -270
  106. package/npm-shrinkwrap.json +2 -2
  107. package/package.json +2 -1
  108. package/skills/skill-forge/SKILL.md +7 -3
@@ -2,13 +2,13 @@
2
2
  // SynaBun Neural Interface — Agents Studio: the view machine
3
3
  // ═══════════════════════════════════════════
4
4
  //
5
- // Where the window is: one of four places of the rail (Library · Create · Review · Teams), or one agent opened from
5
+ // Where the window is: Work, an Agents view (Library, Create or Definition reviews), or a detail opened from
6
6
  // a place, with its tabs (Edit · Revisions · Runs · Test run). A view is a small plain object; `navigate` is the one
7
7
  // function that moves it, so every way in (a rail button, a card, the menu's "Review queue", a link from the
8
8
  // Assistant) lands the same way, and what is saved when the window closes is the view itself.
9
9
  // No DOM and no imports.
10
10
 
11
- export const PLACES = Object.freeze(['library', 'create', 'review', 'teams']);
11
+ export const PLACES = Object.freeze(['work', 'agents']);
12
12
  export const AGENT_TABS = Object.freeze(['edit', 'revisions', 'runs', 'test']);
13
13
  /** The ways into Create (the creator's first step). */
14
14
  export const CREATE_MODES = Object.freeze(['blank', 'template', 'copy', 'import', 'describe']);
@@ -37,111 +37,109 @@ export function keyOf(agent) {
37
37
  return { id, scope: cleanScope(agent?.scope) || { kind: 'global' } };
38
38
  }
39
39
 
40
- export const DEFAULT_VIEW = Object.freeze({ place: 'library', agent: null, tab: 'edit', create: null, teamId: null, from: 'library' });
40
+ export const DEFAULT_VIEW = Object.freeze({ place: 'work', agent: null, tab: 'edit', create: null, teamId: null, from: 'work' });
41
+ const agentPlaces = ['library', 'review', 'create'];
42
+ const validTeam = id => typeof id === 'string' && TEAM_ID_RE.test(id) ? id : null;
43
+
44
+ // Menu links and saved windows from before Work use the four original place names.
45
+ function destination(place, teamId) {
46
+ if (place === 'agents') return 'library';
47
+ if (place === 'teams') return teamId ? 'teams' : 'work';
48
+ if (place === 'work' || agentPlaces.includes(place)) return place;
49
+ return null;
50
+ }
41
51
 
42
- /**
43
- * A link into the Studio (`agents:open` with a detail), normalised: an unknown place falls back to the Library, an
44
- * id is kept only when it has its shape.
45
- * @param {object} detail `{ view | place, id, scope, tab, create, teamId }`
46
- */
47
52
  export function parseOpen(detail) {
48
- const d = detail && typeof detail === 'object' ? detail : {};
49
- const named = typeof d.view === 'string' ? d.view : d.place;
53
+ const d = detail || {};
54
+ const named = d.view || d.place;
50
55
  const id = typeof d.id === 'string' && ID_RE.test(d.id) ? d.id : null;
51
56
  const tab = AGENT_TABS.includes(d.tab) ? d.tab : null;
52
57
  const create = CREATE_MODES.includes(d.create) ? d.create : null;
53
- const teamId = typeof d.teamId === 'string' && TEAM_ID_RE.test(d.teamId) ? d.teamId : null;
54
- let place = PLACES.includes(named) ? named : null;
55
- // The menu's words for the places: "new" is Create, "queue" is Review.
58
+ const teamId = validTeam(d.teamId);
59
+ let place = destination(named, teamId);
56
60
  if (named === 'new') place = 'create';
57
61
  if (named === 'queue') place = 'review';
58
- if (!place) place = id ? 'agent' : create ? 'create' : teamId ? 'teams' : null;
59
- if (id && (place === null || place === 'library' || place === 'agent')) place = 'agent';
62
+ if (id && (!place || place === 'library')) place = 'agent';
63
+ if (!place) place = create ? 'create' : teamId ? 'teams' : null;
60
64
  return { place, id: place === 'agent' ? id : null, scope: place === 'agent' ? (cleanScope(d.scope) || { kind: 'global' }) : null, tab, create, teamId, explicit: !!place };
61
65
  }
62
66
 
63
- /** The view a window starts in: what was saved the last time it closed, when it still reads as a view. */
64
67
  export function initialView(saved) {
65
- const s = saved && typeof saved === 'object' ? saved : {};
66
- const place = PLACES.includes(s.place) || s.place === 'agent' ? s.place : 'library';
67
- const agent = place === 'agent' && typeof s.agent?.id === 'string' && ID_RE.test(s.agent.id) ? { id: s.agent.id, scope: cleanScope(s.agent.scope) || { kind: 'global' } } : null;
68
- return {
69
- place: place === 'agent' && !agent ? 'library' : place,
70
- agent,
71
- tab: AGENT_TABS.includes(s.tab) ? s.tab : 'edit',
72
- create: null,
73
- teamId: typeof s.teamId === 'string' && TEAM_ID_RE.test(s.teamId) ? s.teamId : null,
74
- from: PLACES.includes(s.from) ? s.from : 'library',
75
- };
68
+ const s = typeof saved === 'string' ? { place: saved } : saved || {};
69
+ const teamId = validTeam(s.teamId);
70
+ if (s.place === 'agent') {
71
+ const agent = typeof s.agent?.id === 'string' ? keyOf(s.agent) : null;
72
+ if (!agent) return navigate(DEFAULT_VIEW, { type: 'place', place: 'library' });
73
+ const from = destination(s.from, null) || 'library';
74
+ return { ...DEFAULT_VIEW, place: 'agent', agent, tab: AGENT_TABS.includes(s.tab) ? s.tab : 'edit', from };
75
+ }
76
+ return navigate(DEFAULT_VIEW, { type: 'place', place: destination(s.place, teamId) || 'work', teamId });
76
77
  }
77
78
 
78
- /** What is kept of a view (never the creator's step: a half-made agent is not restored as a place). */
79
79
  export function viewToSave(view) {
80
- return { place: view.place, agent: view.place === 'agent' ? view.agent : null, tab: view.tab, teamId: view.teamId || null, from: view.from };
80
+ return { place: view.place, agent: view.agent, tab: view.tab, teamId: view.teamId, from: view.from };
81
81
  }
82
82
 
83
- /**
84
- * Move the view. Actions:
85
- * { type: 'place', place, create?, teamId? } a place of the rail
86
- * { type: 'agent', key, tab? } open an agent (from the place the view is in)
87
- * { type: 'tab', tab } another tab of the open agent
88
- * { type: 'back' } from an agent to the place it was opened from; from a team to the list
89
- * { type: 'team', teamId } one team, or the list (null)
90
- * { type: 'open', want } a parsed link (parseOpen)
91
- * An action that makes no sense where the view is leaves it as it was (the same object: nothing to draw).
92
- */
93
- export function navigate(view, action) {
94
- const a = action && typeof action === 'object' ? action : {};
83
+ /** Resolve the actual run's pin against the library. Deleted or unpinned agents still have an Assistant run. */
84
+ export function runDestination(open, agents, caps) {
85
+ const key = keyOf(open.agent);
86
+ if (key && caps.has('runs') && (!agents || agents.some(a => agentKeyText(a) === agentKeyText(key)))) {
87
+ return { type: 'agent', key, tab: 'runs', from: 'work' };
88
+ }
89
+ return { type: 'focus-run', runId: open.runId };
90
+ }
91
+
92
+ export function navigate(view, a) {
93
+ if (!a) return view;
95
94
  if (a.type === 'place') {
96
- if (!PLACES.includes(a.place)) return view;
97
- return { ...view, place: a.place, agent: null, create: a.place === 'create' && CREATE_MODES.includes(a.create) ? a.create : null, teamId: a.place === 'teams' ? (a.teamId && TEAM_ID_RE.test(a.teamId) ? a.teamId : null) : view.teamId, from: a.place };
95
+ const teamId = validTeam(a.teamId);
96
+ const place = destination(a.place, teamId);
97
+ if (!place) return view;
98
+ return { ...DEFAULT_VIEW, place, from: place === 'teams' ? 'work' : place,
99
+ create: place === 'create' && CREATE_MODES.includes(a.create) ? a.create : null, teamId: place === 'teams' ? teamId : null };
98
100
  }
99
101
  if (a.type === 'agent') {
100
102
  const key = keyOf(a.key);
101
103
  if (!key) return view;
102
- return { ...view, place: 'agent', agent: key, tab: AGENT_TABS.includes(a.tab) ? a.tab : (view.place === 'agent' && agentKeyText(view.agent) === agentKeyText(key) ? view.tab : 'edit'), create: null, from: view.place === 'agent' ? view.from : (PLACES.includes(view.place) ? view.place : 'library') };
104
+ const sameAgent = view.place === 'agent' && agentKeyText(view.agent) === agentKeyText(key);
105
+ const previous = view.place === 'agent' ? view.from : view.place;
106
+ const from = a.from === 'work' || (view.place === 'agent' && previous === 'work') ? 'work'
107
+ : agentPlaces.includes(previous) ? previous : 'library';
108
+ const tab = AGENT_TABS.includes(a.tab) ? a.tab : (sameAgent ? view.tab : 'edit');
109
+ return { ...DEFAULT_VIEW, place: 'agent', agent: key, from, tab };
103
110
  }
104
111
  if (a.type === 'tab') {
105
112
  if (view.place !== 'agent' || !AGENT_TABS.includes(a.tab) || a.tab === view.tab) return view;
106
113
  return { ...view, tab: a.tab };
107
114
  }
115
+ if (a.type === 'manage-teams') return { ...DEFAULT_VIEW, place: 'teams' };
108
116
  if (a.type === 'team') {
109
- const teamId = typeof a.teamId === 'string' && TEAM_ID_RE.test(a.teamId) ? a.teamId : null;
110
- if (view.place === 'teams' && view.teamId === teamId) return view;
111
- return { ...view, place: 'teams', agent: null, create: null, teamId, from: 'teams' };
117
+ const teamId = validTeam(a.teamId);
118
+ if (!teamId || (view.place === 'teams' && view.teamId === teamId)) return view;
119
+ return { ...DEFAULT_VIEW, place: 'teams', teamId, from: view.place === 'teams' && !view.teamId ? 'manage-teams' : 'work' };
112
120
  }
113
121
  if (a.type === 'back') {
114
- if (view.place === 'agent') return { ...view, place: PLACES.includes(view.from) ? view.from : 'library', agent: null };
115
- if (view.place === 'teams' && view.teamId) return { ...view, teamId: null };
116
- if (view.place === 'create' && view.create) return { ...view, create: null };
122
+ if (view.place === 'teams' && view.from === 'manage-teams') return navigate(view, { type: 'manage-teams' });
123
+ if (view.place === 'teams') return { ...DEFAULT_VIEW };
124
+ if (view.place === 'agent') return navigate(view, { type: 'place', place: view.from });
125
+ if (view.place === 'create') return navigate(view, { type: 'place', place: view.create ? 'create' : 'library' });
117
126
  return view;
118
127
  }
119
128
  if (a.type === 'open') {
120
129
  const want = a.want || {};
121
- if (want.place === 'agent' && want.id) return navigate(view, { type: 'agent', key: { id: want.id, scope: want.scope }, tab: want.tab || undefined });
122
- if (PLACES.includes(want.place)) return navigate(view, { type: 'place', place: want.place, create: want.create, teamId: want.teamId });
123
- return view;
130
+ if (want.place === 'agent' && want.id) return navigate(view, { type: 'agent', key: { id: want.id, scope: want.scope }, tab: want.tab });
131
+ return navigate(view, { ...want, type: 'place' });
124
132
  }
125
133
  return view;
126
134
  }
127
135
 
128
- /**
129
- * The rail: one item per place, the current one marked, a count where a place has one. An open agent keeps the
130
- * place it was opened from marked. `caps` (the server's capabilities, a Set) hides what the server cannot serve;
131
- * while it is unknown (null) nothing is hidden.
132
- * @param {object} view
133
- * @param {{ total?: number, review?: number, teams?: number|null }} [counts]
134
- * @param {Set<string>|null} [caps]
135
- */
136
+ /** Both places are available on older servers. Badges count outstanding decisions only. */
136
137
  export function railModel(view, counts = {}, caps = null) {
137
- const current = view.place === 'agent' ? (PLACES.includes(view.from) ? view.from : 'library') : view.place;
138
- const has = (cap) => !caps || caps.has(cap);
139
- return PLACES.map((place) => ({
140
- place,
141
- current: place === current,
142
- count: place === 'library' ? (counts.total ?? null) : place === 'review' ? (counts.review || null) : place === 'teams' ? (counts.teams || null) : null,
143
- hidden: (place === 'review' && !has('reviews')) || (place === 'create' && !has('drafts')),
144
- })).filter((item) => !item.hidden);
138
+ const work = view.place === 'work' || view.place === 'teams' || (view.place === 'agent' && view.from === 'work');
139
+ return [
140
+ { place: 'work', current: work, count: counts.needsYou || null },
141
+ { place: 'agents', current: !work, count: (!caps || caps.has('reviews')) && counts.review || null },
142
+ ];
145
143
  }
146
144
 
147
145
  /** The tabs of an agent the server can serve (`revisions`, `runs`, `test-run` are capabilities of their own). */
@@ -0,0 +1,86 @@
1
+ import { buildControlResponse, normalizeControlRequest } from '../../assistant/asst-control.js';
2
+ import { buildSynaBunChoiceContent } from '../../cdx/cdx-protocol.js';
3
+ import { attr, html } from '../../skills/studio/sx-dom.js';
4
+
5
+ // ACP and Codex both use MCP form elicitation. The Assistant's form normalizer
6
+ // handles schema values, typed answers and the companion field for a custom choice.
7
+ export function newAnswer({ runId, provider, pending }) {
8
+ const acpForm = pending.protocol?.method === 'elicitation/create';
9
+ const method = acpForm ? 'mcpServer/elicitation/request' : pending.protocol?.method;
10
+ const control = normalizeControlRequest({
11
+ requestId: pending.requestId, provider: acpForm ? 'codex' : pending.protocol?.provider || provider,
12
+ request: { ...pending, method },
13
+ });
14
+ if (control?.synabunChoice) {
15
+ control.questions.forEach((q, i) => { q.multiple = control.synabunChoice.questions[i].multiSelect; });
16
+ }
17
+ return { runId, requestId: pending.requestId, control, fields: (control?.questions || []).map(() => ({ picks: [], text: '' })), busy: false, problem: '' };
18
+ }
19
+
20
+ function customAllowed(q, raw) {
21
+ if (!q.options.length || q.otherField) return true;
22
+ if (q.type) return false;
23
+ return raw?.custom !== false && raw?.isOther !== false;
24
+ }
25
+
26
+ export function answerHTML(draft, say, offline) {
27
+ const { control, fields, requestId } = draft;
28
+ if (!fields.length || draft.problem === 'answerUnsupported') return html`<p role="status">${say('answerUnsupported')}</p>`;
29
+ const disabled = offline || draft.busy;
30
+ return html`<form class="ax-work-answer" data-request="${requestId}">
31
+ ${control.message ? html`<p>${control.message}</p>` : ''}
32
+ ${control.questions.map((q, i) => {
33
+ const id = `ax-work-${requestId}-${i}`;
34
+ const raw = control.rawQuestions?.[i];
35
+ const field = fields[i];
36
+ return html`<fieldset class="sx-field"${attr('disabled', disabled)}>
37
+ <legend class="sx-field-label">${q.text || q.header || say('freeText')}</legend>
38
+ ${q.options.map((o, j) => {
39
+ if (q.otherField && o.value === q.otherValue) return '';
40
+ const label = q.type === 'boolean' && typeof o.value === 'boolean' ? say(o.value ? 'yes' : 'no') : o.label;
41
+ return html`<label class="ax-work-option"><input type="${q.multiple ? 'checkbox' : 'radio'}" id="${id}-${j}" name="${id}" data-q="${i}" data-option="${j}"${attr('checked', field.picks.includes(j))}>
42
+ <span>${label}${o.description ? html`<small>${o.description}</small>` : ''}</span></label>`;
43
+ })}
44
+ ${customAllowed(q, raw) ? html`<label class="ax-work-custom">${say(q.options.length ? 'custom' : 'freeText')}
45
+ <input class="sx-input" id="${id}-text" type="${raw?.isSecret ? 'password' : ['integer', 'number'].includes(q.type) ? 'number' : 'text'}"${attr('step', q.type === 'number' ? 'any' : false)} data-q="${i}" value="${field.text}" autocomplete="off"></label>` : ''}
46
+ </fieldset>`;
47
+ })}
48
+ ${draft.problem ? html`<p role="status">${say(draft.problem)}</p>` : ''}
49
+ <button class="sx-btn sx-btn--primary" id="ax-work-send-${requestId}" type="submit"${attr('disabled', disabled)}>${say('submit')}</button>
50
+ </form>`;
51
+ }
52
+
53
+ export function editAnswer(draft, input) {
54
+ if (!draft || draft.busy || input.dataset.q === undefined) return;
55
+ const i = Number(input.dataset.q);
56
+ const q = draft.control.questions[i];
57
+ const f = draft.fields[i];
58
+ if (!f || !q) return;
59
+ if (input.dataset.option !== undefined) {
60
+ const pick = Number(input.dataset.option);
61
+ f.picks = (q.multiple ? f.picks : []).filter(j => j !== pick);
62
+ if (input.checked) f.picks.push(pick);
63
+ if (!q.multiple) {
64
+ f.text = '';
65
+ const custom = input.closest('fieldset')?.querySelector('.sx-input');
66
+ if (custom) custom.value = '';
67
+ }
68
+ } else {
69
+ f.text = input.value;
70
+ if (!q.multiple && f.text) {
71
+ f.picks = [];
72
+ for (const el of input.closest('fieldset')?.querySelectorAll('[data-option]') || []) el.checked = false;
73
+ }
74
+ }
75
+ }
76
+
77
+ export function answerBody(draft) {
78
+ const answers = draft.fields.map((f, i) => [...f.picks.map(j => draft.control.questions[i].options[j].label), f.text.trim()].filter(Boolean));
79
+ if (!answers.length || answers.some((list, i) => !list.length && draft.control.questions[i].required !== false)) return null;
80
+ if (draft.control.synabunChoice) {
81
+ const questions = draft.control.synabunChoice.questions;
82
+ const choices = Object.fromEntries(questions.map((q, i) => [q.id, { answers: answers[i] }]));
83
+ return { behavior: 'allow', result: { action: 'accept', content: buildSynaBunChoiceContent(questions, choices) } };
84
+ }
85
+ return buildControlResponse(draft.control, { behavior: 'allow', answers });
86
+ }
@@ -0,0 +1,305 @@
1
+ import { attr, html, ICONS, setHTML } from '../../skills/studio/sx-dom.js';
2
+ import { baseName } from './ax-library.js';
3
+ import { buildWork, WORK_COPY } from './ax-work.js';
4
+ import { answerBody, answerHTML, editAnswer, newAnswer } from './ax-work-answer.js';
5
+
6
+ const prefix = 'agentsStudio.work.';
7
+ const groupKeys = { 'needs-you': 'needsYou', active: 'active', 'in-review': 'inReview', finished: 'finished' };
8
+ let life = null;
9
+ let refreshTimer = 0;
10
+ const invalidTeams = new Set();
11
+
12
+ function words(t, name, params = {}) {
13
+ const key = name.startsWith(prefix) ? name : prefix + name;
14
+ const translated = t(key, params);
15
+ if (translated && translated !== key) return translated;
16
+ return WORK_COPY[key].replace(/\{(\w+)\}/g, (_, k) => params[k] ?? '');
17
+ }
18
+
19
+ export function newWorkState() {
20
+ return { model: null, displayed: null, teams: null, runs: null, details: new Map(), missingDetails: false,
21
+ loading: false, seq: 0, offline: false, drafts: new Map(), expanded: null, consumed: new Set(),
22
+ notice: '', returnTo: null, scrollTop: 0 };
23
+ }
24
+
25
+ export function workNeedsYou(st) { return st.model?.counts.needsYou ?? 0; }
26
+
27
+ export function leaveWork() { life?.abort(); life = null; }
28
+
29
+ export function stopWork() {
30
+ leaveWork();
31
+ clearTimeout(refreshTimer);
32
+ refreshTimer = 0;
33
+ invalidTeams.clear();
34
+ }
35
+
36
+ function tell(ctx, st, key) {
37
+ st.notice = key;
38
+ if (ctx.view.place === 'work') ctx.announce?.(words(ctx.t, key));
39
+ }
40
+
41
+ function draw(ctx) { ctx.render({ keepFocus: true }); }
42
+ const taskList = model => model?.groups.flatMap(g => g.tasks) || [];
43
+ const requestOf = task => task?.question?.pending.requestId;
44
+
45
+ function reconcileAnswers(ctx, st, runs) {
46
+ const byId = new Map(runs.map(r => [r.runId, r]));
47
+ for (const [id, draft] of st.drafts) {
48
+ const run = byId.get(draft.runId);
49
+ if (draft.busy || (!run && runs.length >= 500) || run?.pending?.some(p => p.requestId === id)) continue;
50
+ if (st.expanded === id) { st.expanded = null; tell(ctx, st, 'stale'); }
51
+ st.drafts.delete(id);
52
+ }
53
+ const pending = new Set(runs.flatMap(r => (r.pending || []).map(p => p.requestId)));
54
+ for (const id of st.consumed) if (!pending.has(id)) st.consumed.delete(id);
55
+ }
56
+
57
+ function visibleRuns(st, runs) {
58
+ if (!runs || !st.consumed.size) return runs;
59
+ return runs.map(run => ({ ...run, pending: run.pending?.filter(p => !st.consumed.has(p.requestId)) }));
60
+ }
61
+
62
+ // Status/detail reads inspect git on the server. Only open teams get one;
63
+ // a burst of worker changes reuses other teams' details.
64
+ async function readDetails(ctx, rows, cached, changed, isCurrent) {
65
+ const details = new Map();
66
+ const queue = [];
67
+ for (const row of rows) {
68
+ if (!['running', 'needs_attention', 'ready'].includes(row.status)) continue;
69
+ const saved = cached.get(row.id);
70
+ if (changed && !changed.has(row.id) && saved?.status === row.status) details.set(row.id, saved);
71
+ else queue.push(row);
72
+ }
73
+ let i = 0;
74
+ let missing = false;
75
+ async function lane() {
76
+ while (i < queue.length && isCurrent()) {
77
+ const row = queue[i++];
78
+ try {
79
+ const { team } = await ctx.api.team(row.id);
80
+ if (team) details.set(row.id, team);
81
+ else missing = true;
82
+ } catch { missing = true; }
83
+ }
84
+ }
85
+ await Promise.all(Array.from({ length: Math.min(3, queue.length) }, lane));
86
+ return { details, missing };
87
+ }
88
+
89
+ export async function loadWork(ctx, st, { changedTeams = null } = {}) {
90
+ const seq = ++st.seq;
91
+ const gen = ctx.gen();
92
+ const current = () => st.seq === seq && ctx.alive(gen);
93
+ st.loading = true;
94
+ try {
95
+ const reuseTeams = changedTeams?.size === 0 && st.teams && !st.offline && !st.missingDetails;
96
+ let teamRead, runRead;
97
+ if (reuseTeams) {
98
+ [runRead] = await Promise.allSettled([ctx.api.workRuns()]);
99
+ if (!current()) return;
100
+ // A worker event has no new team projection. If the worker read failed,
101
+ // probe the other source to distinguish partial coverage from disconnection.
102
+ if (runRead.status === 'fulfilled') teamRead = { value: { available: true, teams: st.teams } };
103
+ else [teamRead] = await Promise.allSettled([ctx.api.teams()]);
104
+ } else {
105
+ [teamRead, runRead] = await Promise.allSettled([ctx.api.teams(), ctx.api.workRuns()]);
106
+ }
107
+ if (!current()) return;
108
+ const teams = teamRead.value?.available && Array.isArray(teamRead.value.teams) ? teamRead.value.teams : null;
109
+ const runs = Array.isArray(runRead.value?.runs) ? runRead.value.runs : null;
110
+ const networkFailure = read => read.status === 'rejected' && !read.reason?.status;
111
+ const offline = globalThis.navigator?.onLine === false || [teamRead, runRead].every(networkFailure);
112
+ const previous = st.model;
113
+ const previousNotice = st.notice;
114
+ const { details, missing } = teams ? await readDetails(ctx, teams, st.details, changedTeams, current) : { details: new Map(), missing: false };
115
+ if (!current()) return;
116
+ if (runs) reconcileAnswers(ctx, st, runs);
117
+ if (teams || !offline) { st.teams = teams; st.details = details; }
118
+ if (runs || !offline) st.runs = runs;
119
+ st.offline = offline;
120
+ st.missingDetails = missing;
121
+ st.model = buildWork({ teams: st.teams, teamDetails: st.details, runs: visibleRuns(st, st.runs), now: Date.now() });
122
+ st.model.coverage.missing = [...(!teams ? ['teams'] : []), ...(!runs ? ['runs'] : [])];
123
+ if (previous && ctx.view.place === 'work' && previousNotice === st.notice && !st.model.coverage.missing.length) {
124
+ if (previous.counts.needsYou !== st.model.counts.needsYou) {
125
+ ctx.announce?.(words(ctx.t, 'needsYou') + ' · ' + st.model.counts.needsYou);
126
+ } else {
127
+ const old = new Map(taskList(previous).map(t => [t.id, t.reason.key]));
128
+ const changed = taskList(st.model).find(t => old.get(t.id) !== t.reason.key);
129
+ if (changed) ctx.announce?.(words(ctx.t, changed.reason.key, changed.reason.params));
130
+ }
131
+ }
132
+ } finally {
133
+ if (st.seq === seq) st.loading = false;
134
+ }
135
+ }
136
+
137
+ export function onWorkChanged(ctx, st, event = {}) {
138
+ if (event.teamId) invalidTeams.add(event.teamId);
139
+ else if (event.type === 'assistant:team-changed') invalidTeams.add('*');
140
+ if (refreshTimer) return;
141
+ const gen = ctx.gen();
142
+ const refresh = async () => {
143
+ if (!ctx.alive(gen)) { refreshTimer = 0; return; }
144
+ if (st.loading) { refreshTimer = setTimeout(refresh, 250); return; }
145
+ refreshTimer = 0;
146
+ const changedTeams = invalidTeams.has('*') ? null : new Set(invalidTeams);
147
+ invalidTeams.clear();
148
+ await loadWork(ctx, st, { changedTeams });
149
+ if (ctx.alive(gen)) {
150
+ if (ctx.view.place === 'work') draw(ctx);
151
+ else ctx.refreshWorkBadge?.();
152
+ }
153
+ };
154
+ refreshTimer = setTimeout(refresh, 250);
155
+ }
156
+
157
+ function rowHTML(task, st, say) {
158
+ const disabled = attr('disabled', st.offline);
159
+ const qid = requestOf(task);
160
+ const expanded = !!qid && st.expanded === qid;
161
+ const title = task.title || say('untitled');
162
+ const workers = task.workers === 1 ? say('oneWorker') : task.workers ? say('teamOf', { count: task.workers }) : say('noWorkers');
163
+ return html`<li class="ax-work-item" data-task="${task.id}" aria-labelledby="ax-work-title-${task.id}">
164
+ <div class="ax-work-grid">
165
+ <button type="button" class="sx-link ax-work-title" id="ax-work-title-${task.id}" data-act="open"${disabled}>${title}</button>
166
+ <span class="ax-work-reason">${say(task.reason.key, task.reason.params)}</span>
167
+ <span class="ax-work-who">${baseName(task.project) || say('noProject')}<small>${workers}</small></span>
168
+ <button type="button" class="sx-btn sx-btn--sm" id="ax-work-action-${task.id}" data-act="${task.primary.action}"${disabled}
169
+ ${attr('aria-expanded', qid ? String(expanded) : null)}>${say(task.primary.key, task.reason.params)}</button>
170
+ </div>${expanded ? answerHTML(st.drafts.get(qid), say, st.offline) : ''}
171
+ </li>`;
172
+ }
173
+
174
+ function bodyHTML(model, st, say) {
175
+ if (!model) return html`<p role="status">${say('loading')}</p>`;
176
+ const { missing, runsCapped } = model.coverage;
177
+ const complete = !st.offline && !missing.length && !runsCapped && !st.missingDetails;
178
+ const empty = complete && model.groups.slice(0, 3).every(g => !g.tasks.length);
179
+ return html`${st.offline ? html`<p class="sx-note-warn" role="status">${say('offline')}</p>` : missing.map(s =>
180
+ html`<p class="sx-note-warn" role="status">${say(s === 'teams' ? 'missingTeams' : 'missingRuns')}</p>`)}
181
+ ${st.missingDetails ? html`<p role="status">${say('missingDetails')}</p>` : ''}
182
+ ${runsCapped ? html`<p role="status">${say('capped')}</p>` : ''}
183
+ ${empty ? html`<div class="sx-empty">${ICONS.ok}<h4 class="sx-empty-title">${say('empty')}</h4></div>` : ''}
184
+ ${taskList(model).length ? html`<div class="ax-work-cols ax-work-grid" aria-hidden="true"><span>${say('task')}</span><span>${say('progress')}</span><span>${say('who')}</span></div>` : ''}
185
+ ${model.groups.map(group => html`<section class="ax-work-group" id="ax-work-${group.id}" aria-labelledby="ax-work-h-${group.id}">
186
+ <h4 class="sx-section-title" id="ax-work-h-${group.id}">${say(groupKeys[group.id])} <small>${group.tasks.length}</small></h4>
187
+ ${group.tasks.length ? html`<ul>${group.tasks.map(task => rowHTML(task, st, say))}</ul>` : ''}
188
+ </section>`)}
189
+ ${st.notice ? html`<p class="ax-work-notice">${say(st.notice)}</p>` : ''}`;
190
+ }
191
+
192
+ function stylesheet(doc) {
193
+ if (doc.getElementById('ax-work-style')) return;
194
+ const link = doc.createElement('link');
195
+ link.id = 'ax-work-style';
196
+ link.rel = 'stylesheet';
197
+ link.href = new URL('./ax-work.css', import.meta.url).href;
198
+ doc.head.append(link);
199
+ }
200
+
201
+ export function renderWork(main, ctx, st) {
202
+ leaveWork();
203
+ life = new AbortController();
204
+ const { signal } = life;
205
+ const doc = main.ownerDocument;
206
+ stylesheet(doc);
207
+ if (globalThis.navigator?.onLine === false) st.offline = true;
208
+ const gen = ctx.gen();
209
+ const redraw = () => { if (ctx.alive(gen) && ctx.view.place === 'work') draw(ctx); };
210
+ const reload = async () => { await loadWork(ctx, st); redraw(); };
211
+ const say = (key, params) => words(ctx.t, key, params);
212
+ const focused = doc.activeElement?.closest('[data-task]');
213
+ const previousFocus = focused && doc.activeElement.id;
214
+ // During traversal keep the visible order until focus leaves the task list.
215
+ // A consumed question or lost connection must still update immediately.
216
+ const latest = new Map(taskList(st.model).map(task => [task.id, task]));
217
+ const canHold = focused && main.contains(focused) && st.displayed && !st.offline && !st.model.coverage.missing.length &&
218
+ taskList(st.displayed).every(task => latest.has(task.id) && requestOf(latest.get(task.id)) === requestOf(task));
219
+ let model = st.model;
220
+ if (canHold) {
221
+ model = { ...st.model, groups: st.displayed.groups.map(g => {
222
+ const currentGroup = new Map(st.model.groups.find(group => group.id === g.id).tasks.map(t => [t.id, t]));
223
+ return { ...g, tasks: g.tasks.map(t => currentGroup.get(t.id) || t) };
224
+ }) };
225
+ }
226
+ st.displayed = model;
227
+ setHTML(main, html`<section class="sx-place ax-place" aria-labelledby="ax-work-heading">
228
+ <header class="sx-place-head"><h3 class="sx-place-title" id="ax-work-heading" tabindex="-1">${say('title')}</h3>
229
+ <span class="sx-spacer"></span><button class="sx-btn sx-btn--sm" id="ax-work-refresh" type="button" data-act="refresh">${ICONS.update}${say(st.offline ? 'retry' : 'refresh')}</button></header>
230
+ <div class="sx-place-scroll ax-work-scroll" tabindex="0" aria-labelledby="ax-work-heading">${bodyHTML(model, st, say)}</div>
231
+ </section>`);
232
+ const scroller = main.querySelector('.ax-work-scroll');
233
+ if (st.returnTo) {
234
+ const opener = doc.getElementById(st.returnTo);
235
+ scroller.scrollTop = st.scrollTop;
236
+ (opener || doc.getElementById('ax-work-heading'))?.focus({ preventScroll: true });
237
+ st.returnTo = null;
238
+ } else if (previousFocus && !doc.getElementById(previousFocus)) {
239
+ const action = doc.getElementById('ax-work-action-' + focused.dataset.task);
240
+ (action && !action.disabled ? action : doc.getElementById('ax-work-refresh'))?.focus({ preventScroll: true });
241
+ }
242
+ if (!model && !st.loading) void reload();
243
+ const draft = () => st.drafts.get(st.expanded);
244
+ main.addEventListener('input', e => editAnswer(draft(), e.target), { signal });
245
+ main.addEventListener('focusout', e => {
246
+ if (canHold && e.relatedTarget && !e.relatedTarget.closest('[data-task]')) queueMicrotask(() => { if (!signal.aborted) redraw(); });
247
+ }, { signal });
248
+ main.addEventListener('click', e => {
249
+ const btn = e.target.closest('button[data-act]');
250
+ if (!btn || btn.disabled) return;
251
+ if (btn.dataset.act === 'refresh') { void reload(); return; }
252
+ const task = latest.get(btn.closest('[data-task]')?.dataset.task);
253
+ if (!task || st.offline) return;
254
+ if (btn.dataset.act === 'answer' && task.question) {
255
+ const id = requestOf(task);
256
+ if (!st.drafts.has(id)) st.drafts.set(id, newAnswer(task.question));
257
+ st.expanded = st.expanded === id ? null : id;
258
+ st.notice = '';
259
+ redraw();
260
+ if (st.expanded) main.querySelector('.ax-work-answer input')?.focus();
261
+ } else {
262
+ st.returnTo = btn.id;
263
+ st.scrollTop = scroller.scrollTop;
264
+ ctx.go(task.open);
265
+ }
266
+ }, { signal });
267
+ main.addEventListener('submit', async e => {
268
+ e.preventDefault();
269
+ const d = draft();
270
+ const task = d && taskList(st.model).find(t => requestOf(t) === d.requestId);
271
+ if (!task || d.busy || st.offline || e.target.dataset.request !== d.requestId) return;
272
+ const response = answerBody(d);
273
+ if (!response) { d.problem = 'required'; redraw(); return; }
274
+ d.busy = true;
275
+ d.problem = '';
276
+ redraw();
277
+ try {
278
+ const result = await ctx.api.answerWorkerQuestion(d.runId, d.requestId, response);
279
+ if (!ctx.alive(gen)) return;
280
+ st.consumed.add(d.requestId);
281
+ st.drafts.delete(d.requestId);
282
+ if (st.expanded === d.requestId) {
283
+ st.expanded = null;
284
+ st.returnTo = 'ax-work-action-' + task.id;
285
+ st.scrollTop = scroller.scrollTop;
286
+ }
287
+ tell(ctx, st, result.stale ? 'stale' : 'sent');
288
+ st.runs = (st.runs || []).map(r => result.run?.runId === r.runId ? result.run : r);
289
+ st.seq++;
290
+ st.model = buildWork({ teams: st.teams, teamDetails: st.details, runs: visibleRuns(st, st.runs), now: Date.now() });
291
+ redraw();
292
+ await reload();
293
+ } catch (error) {
294
+ if (!ctx.alive(gen)) return;
295
+ d.problem = [404, 405, 501].includes(error.status) ? 'answerUnsupported' : 'answerFailed';
296
+ ctx.announce?.(say(d.problem));
297
+ if (!error.status) await reload();
298
+ } finally {
299
+ d.busy = false;
300
+ redraw();
301
+ }
302
+ }, { signal });
303
+ doc.defaultView?.addEventListener('offline', () => { st.offline = true; redraw(); }, { signal });
304
+ doc.defaultView?.addEventListener('online', reload, { signal });
305
+ }