@agentshouse/kit 0.2.1-ce3d2bb67177c → 0.2.1-ce8e5419af3f9

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 (146) hide show
  1. package/README.md +17 -18
  2. package/dist/acp.js +58 -7
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +58 -32
  5. package/dist/authority-main.js +3 -3
  6. package/dist/bridge.js +5 -5
  7. package/dist/building.js +50 -0
  8. package/dist/calls.js +12 -4
  9. package/dist/chunks.js +49 -0
  10. package/dist/clis.js +46 -44
  11. package/dist/connection.js +28 -33
  12. package/dist/content.js +63 -0
  13. package/dist/conversations.js +344 -127
  14. package/dist/copies.js +294 -148
  15. package/dist/end.js +8 -2
  16. package/dist/events.js +742 -210
  17. package/dist/files.js +35 -19
  18. package/dist/git.js +46 -12
  19. package/dist/grok.js +39 -0
  20. package/dist/home.js +0 -7
  21. package/dist/house-cli.js +29 -57
  22. package/dist/house-main.js +3 -3
  23. package/dist/instructions.js +29 -11
  24. package/dist/kit-cli.js +3 -6
  25. package/dist/kit-main.js +3 -3
  26. package/dist/login.js +5 -3
  27. package/dist/logout.js +1 -1
  28. package/dist/mcp.js +2 -0
  29. package/dist/placement.js +10 -18
  30. package/dist/relay.js +21 -0
  31. package/dist/resident.js +47 -26
  32. package/dist/scope.js +12 -4
  33. package/dist/scripts.js +255 -0
  34. package/dist/secret-input.js +1 -1
  35. package/dist/sign-in.js +3 -2
  36. package/dist/silence.js +28 -0
  37. package/dist/skills.js +41 -96
  38. package/dist/transcription.js +37 -24
  39. package/dist/translate.js +18 -9
  40. package/dist/update.js +109 -120
  41. package/dist/wire.js +23 -5
  42. package/dist/work.js +9 -2
  43. package/package.json +21 -20
  44. package/dist/bootstrap.json +0 -24
  45. package/dist/chatgpt.js +0 -32
  46. package/dist/clis-main.js +0 -23
  47. package/dist/parts.js +0 -82
  48. package/how-we-work.md +0 -33
  49. package/skills/ask-matt/LICENSE +0 -21
  50. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  51. package/skills/ask-matt/SKILL.md +0 -97
  52. package/skills/ask-matt/agents/openai.yaml +0 -5
  53. package/skills/code-review/LICENSE +0 -21
  54. package/skills/code-review/SKILL.md +0 -89
  55. package/skills/code-review/agents/openai.yaml +0 -3
  56. package/skills/codebase-design/DEEPENING.md +0 -37
  57. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  58. package/skills/codebase-design/LICENSE +0 -21
  59. package/skills/codebase-design/SKILL.md +0 -114
  60. package/skills/codebase-design/agents/openai.yaml +0 -3
  61. package/skills/diagnosing-bugs/LICENSE +0 -21
  62. package/skills/diagnosing-bugs/SKILL.md +0 -138
  63. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  64. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  65. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  66. package/skills/domain-modeling/GLOSSARY-FORMAT.md +0 -60
  67. package/skills/domain-modeling/LICENSE +0 -21
  68. package/skills/domain-modeling/SKILL.md +0 -74
  69. package/skills/domain-modeling/agents/openai.yaml +0 -3
  70. package/skills/grill-me/LICENSE +0 -21
  71. package/skills/grill-me/SKILL.md +0 -7
  72. package/skills/grill-me/agents/openai.yaml +0 -5
  73. package/skills/grill-with-docs/LICENSE +0 -21
  74. package/skills/grill-with-docs/SKILL.md +0 -7
  75. package/skills/grill-with-docs/agents/openai.yaml +0 -5
  76. package/skills/grilling/LICENSE +0 -21
  77. package/skills/grilling/SKILL.md +0 -30
  78. package/skills/grilling/agents/openai.yaml +0 -3
  79. package/skills/handoff/LICENSE +0 -21
  80. package/skills/handoff/SKILL.md +0 -16
  81. package/skills/handoff/agents/openai.yaml +0 -5
  82. package/skills/implement/LICENSE +0 -21
  83. package/skills/implement/SKILL.md +0 -17
  84. package/skills/implement/agents/openai.yaml +0 -5
  85. package/skills/implement-spec/LICENSE +0 -21
  86. package/skills/implement-spec/SKILL.md +0 -40
  87. package/skills/implement-spec/agents/openai.yaml +0 -5
  88. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  89. package/skills/improve-codebase-architecture/LICENSE +0 -21
  90. package/skills/improve-codebase-architecture/SKILL.md +0 -71
  91. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -5
  92. package/skills/pr/CREDITS.md +0 -3
  93. package/skills/pr/LICENSE +0 -21
  94. package/skills/pr/SKILL.md +0 -170
  95. package/skills/pr/agents/openai.yaml +0 -3
  96. package/skills/prototype/LICENSE +0 -21
  97. package/skills/prototype/LOGIC.md +0 -67
  98. package/skills/prototype/SKILL.md +0 -26
  99. package/skills/prototype/UI.md +0 -112
  100. package/skills/prototype/agents/openai.yaml +0 -3
  101. package/skills/research/LICENSE +0 -21
  102. package/skills/research/SKILL.md +0 -12
  103. package/skills/research/agents/openai.yaml +0 -3
  104. package/skills/retro/LICENSE +0 -21
  105. package/skills/retro/SKILL.md +0 -44
  106. package/skills/retro/agents/openai.yaml +0 -5
  107. package/skills/tdd/LICENSE +0 -21
  108. package/skills/tdd/SKILL.md +0 -38
  109. package/skills/tdd/agents/openai.yaml +0 -3
  110. package/skills/tdd/mocking.md +0 -59
  111. package/skills/tdd/tests.md +0 -77
  112. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  113. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  114. package/skills/teach/LICENSE +0 -21
  115. package/skills/teach/MISSION-FORMAT.md +0 -31
  116. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  117. package/skills/teach/SKILL.md +0 -140
  118. package/skills/teach/agents/openai.yaml +0 -5
  119. package/skills/to-questionnaire/LICENSE +0 -21
  120. package/skills/to-questionnaire/SKILL.md +0 -54
  121. package/skills/to-questionnaire/agents/openai.yaml +0 -5
  122. package/skills/to-spec/LICENSE +0 -21
  123. package/skills/to-spec/SKILL.md +0 -75
  124. package/skills/to-spec/agents/openai.yaml +0 -5
  125. package/skills/to-tickets/LICENSE +0 -21
  126. package/skills/to-tickets/SKILL.md +0 -105
  127. package/skills/to-tickets/agents/openai.yaml +0 -5
  128. package/skills/triage/AGENT-BRIEF.md +0 -207
  129. package/skills/triage/LICENSE +0 -21
  130. package/skills/triage/OUT-OF-SCOPE.md +0 -105
  131. package/skills/triage/SKILL.md +0 -112
  132. package/skills/triage/agents/openai.yaml +0 -5
  133. package/skills/wait-what/LICENSE +0 -21
  134. package/skills/wait-what/SKILL.md +0 -7
  135. package/skills/wait-what/agents/openai.yaml +0 -5
  136. package/skills/wayfinder/LICENSE +0 -21
  137. package/skills/wayfinder/SKILL.md +0 -128
  138. package/skills/wayfinder/agents/openai.yaml +0 -5
  139. package/skills/wizard/LICENSE +0 -21
  140. package/skills/wizard/SKILL.md +0 -44
  141. package/skills/wizard/agents/openai.yaml +0 -3
  142. package/skills/wizard/template.sh +0 -223
  143. package/skills/writing-for-agents/LICENSE +0 -21
  144. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  145. package/skills/writing-for-agents/SKILL.md +0 -81
  146. package/skills/writing-for-agents/agents/openai.yaml +0 -3
package/dist/clis.js CHANGED
@@ -4,7 +4,8 @@ import { constants, readFileSync } from 'node:fs';
4
4
  import { access, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
5
5
  import { homedir, userInfo } from 'node:os';
6
6
  import { delimiter, dirname, isAbsolute, join } from 'node:path';
7
- import { kitHome } from './home.js';
7
+ import { releaseDirectory } from './placement.js';
8
+ import { childEnvironment } from './relay.js';
8
9
  const HOUSE_EXECUTABLES = /^host_executable\(name = "house", paths = (\[.*\])\)$/m;
9
10
  function houseRule(houses) {
10
11
  return `prefix_rule(pattern = ["house"], decision = "allow")\nhost_executable(name = "house", paths = ${JSON.stringify(houses)})\n`;
@@ -14,10 +15,12 @@ const RAW_SUBTYPES = [
14
15
  'task_started',
15
16
  'task_updated',
16
17
  'task_notification',
18
+ 'task_progress',
17
19
  'session_state_changed',
18
20
  'hook_started',
19
21
  'hook_response',
20
22
  ];
23
+ const RAW_TYPES = ['result', 'user', 'assistant', 'rate_limit_event', 'prompt_suggestion'];
21
24
  async function executable(path) {
22
25
  try {
23
26
  await access(path, constants.X_OK);
@@ -60,6 +63,14 @@ export async function allowHouseInCodex(path) {
60
63
  await rename(temporary, file);
61
64
  }
62
65
  async function nothing() { }
66
+ function claudeQuestionFields(request) {
67
+ const properties = request.requestedSchema?.properties ?? {};
68
+ return Object.keys(properties).filter((name) => properties[name]._meta?.jetbrains?.air?.customAnswer !== undefined);
69
+ }
70
+ function codexQuestionFields(request) {
71
+ const { _meta, requestedSchema } = request;
72
+ return _meta?.codex === undefined ? [] : (requestedSchema?.required ?? []);
73
+ }
63
74
  function answered(error) {
64
75
  return typeof error === 'object' && error !== null ? error : {};
65
76
  }
@@ -69,8 +80,9 @@ function bridgeInClaudeSandbox(bridge) {
69
80
  export const CLIS = {
70
81
  'codex-acp': {
71
82
  bin: 'codex',
72
- minimum: '0.159.1',
83
+ minimum: '0.165.0',
73
84
  install: 'curl -fsSL https://chatgpt.com/codex/install.sh | sh',
85
+ update: 'codex update',
74
86
  adapter: {
75
87
  package: '@agentclientprotocol/codex-acp',
76
88
  bin: 'codex-acp',
@@ -84,16 +96,17 @@ export const CLIS = {
84
96
  const { code, data } = answered(error);
85
97
  return code === -32603 && typeof data?.details === 'string' && data.details.startsWith('no rollout found');
86
98
  },
87
- renames: true,
88
99
  allowHouse: allowHouseInCodex,
100
+ questionFields: codexQuestionFields,
89
101
  signedIn: { command: ['login', 'status'] },
90
102
  login: { args: ['login', '--device-auth'], code: 'show' },
91
103
  air: ['asyncTasks', 'nativeSubagentSessions'],
92
104
  },
93
105
  'claude-agent-acp': {
94
106
  bin: 'claude',
95
- minimum: '2.1.286',
107
+ minimum: '2.1.316',
96
108
  install: 'curl -fsSL https://claude.ai/install.sh | bash',
109
+ update: 'claude update',
97
110
  adapter: {
98
111
  package: '@agentclientprotocol/claude-agent-acp',
99
112
  bin: 'claude-agent-acp',
@@ -102,20 +115,19 @@ export const CLIS = {
102
115
  },
103
116
  args: [],
104
117
  fullAccess: 'bypassPermissions',
105
- sessionMeta: (bridge, title) => ({
118
+ sessionMeta: (bridge) => ({
106
119
  claudeCode: {
107
120
  options: {
108
121
  allowedTools: ['Bash(house:*)'],
109
122
  includeHookEvents: true,
110
- title,
111
123
  settings: { sandbox: { network: bridgeInClaudeSandbox(bridge) } },
112
124
  },
113
- emitRawSDKMessages: RAW_SUBTYPES.map((subtype) => ({ type: 'system', subtype })),
125
+ emitRawSDKMessages: [...RAW_SUBTYPES.map((subtype) => ({ type: 'system', subtype })), ...RAW_TYPES.map((type) => ({ type }))],
114
126
  },
115
127
  }),
116
128
  unknownSession: (error) => answered(error).code === -32002,
117
- renames: false,
118
129
  allowHouse: nothing,
130
+ questionFields: claudeQuestionFields,
119
131
  signedIn: { command: ['auth', 'status'] },
120
132
  login: { args: ['auth', 'login', '--claudeai'], code: 'collect', rejected: 'Invalid code' },
121
133
  air: ['asyncTasks', 'sessionFailure'],
@@ -124,13 +136,14 @@ export const CLIS = {
124
136
  bin: 'grok',
125
137
  minimum: '1.0.46',
126
138
  install: 'curl -fsSL https://x.ai/cli/install.sh | bash',
139
+ update: 'grok update',
127
140
  adapter: null,
128
141
  args: ['--sandbox', 'off', 'agent', '--always-approve', '--no-leader', 'stdio'],
129
142
  fullAccess: null,
130
143
  sessionMeta: () => ({}),
131
144
  unknownSession: (error) => answered(error).data?.code === 'FS_NOT_FOUND',
132
- renames: false,
133
145
  allowHouse: nothing,
146
+ questionFields: () => [],
134
147
  signedIn: { initializeMeta: 'defaultAuthMethodId' },
135
148
  login: { args: ['login', '--device-auth'], code: 'show' },
136
149
  air: ['asyncTasks'],
@@ -138,37 +151,21 @@ export const CLIS = {
138
151
  };
139
152
  const KIT_PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
140
153
  export const KIT_RELEASE = KIT_PACKAGE.version;
141
- const PROXY = /^https?_proxy$/i;
142
154
  const VERSION = /\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?/;
143
- // An install still running after fifteen minutes is ended and reported as failed, so a hung download cannot hold its CLI's report.
155
+ // An install or update still running after fifteen minutes is ended as failed, so a hung download can neither hold its CLI's report nor keep the Kit busy.
144
156
  const INSTALL_MS = 15 * 60_000;
145
157
  // A login shell or a version read is ended after half a minute, so a profile that waits for input cannot stall the report.
146
158
  const READ_MS = 30_000;
147
159
  const CAUSE_CHARACTERS = 4000;
148
- function prefix(kind) {
149
- return join(kitHome(), 'agents', kind);
150
- }
151
160
  export function adapterCommand(kind) {
152
- return join(prefix(kind), 'node_modules', '.bin', CLIS[kind].adapter.bin);
153
- }
154
- async function installedAdapter(kind) {
155
- try {
156
- const manifest = join(prefix(kind), 'node_modules', CLIS[kind].adapter.package, 'package.json');
157
- return JSON.parse(await readFile(manifest, 'utf8')).version;
158
- }
159
- catch {
160
- return null;
161
- }
162
- }
163
- export function withoutProxy() {
164
- return Object.fromEntries(Object.entries(process.env).filter(([name]) => !PROXY.test(name)));
161
+ return join(releaseDirectory(KIT_RELEASE), 'adapters', kind, 'node_modules', '.bin', CLIS[kind].adapter.bin);
165
162
  }
166
163
  export function run(command, args, timeoutMs, detached = false, signal) {
167
164
  return new Promise((resolve) => {
168
165
  const child = spawn(command, args, {
169
166
  stdio: ['ignore', 'pipe', 'pipe'],
170
167
  timeout: timeoutMs,
171
- env: withoutProxy(),
168
+ env: childEnvironment(),
172
169
  detached,
173
170
  signal: detached ? undefined : signal,
174
171
  });
@@ -202,19 +199,18 @@ export function run(command, args, timeoutMs, detached = false, signal) {
202
199
  export function failureOf(ran, program) {
203
200
  return ran.output.trim().slice(-CAUSE_CHARACTERS) || `${program} exited with ${ran.status ?? 'a signal'}`;
204
201
  }
205
- export async function installAdapter(kind, signal) {
206
- const adapter = CLIS[kind].adapter;
207
- if (adapter === null)
208
- return null;
209
- const release = KIT_PACKAGE.peerDependencies[adapter.package];
210
- if ((await installedAdapter(kind)) === release)
211
- return null;
212
- const ran = await run('npm', ['install', '--prefix', prefix(kind), '--cache', join(kitHome(), 'npm-cache'), '--no-save', '--no-audit', '--no-fund', '--omit=optional', `${adapter.package}@${release}`], INSTALL_MS, true, signal);
213
- return ran.status === 0 ? null : failureOf(ran, 'npm');
202
+ export function adapterArchive(kind) {
203
+ return `${kind}-${KIT_PACKAGE.peerDependencies[CLIS[kind].adapter.package]}.tar.gz`;
214
204
  }
215
- export async function installCli(kind, signal) {
216
- const ran = await run('bash', ['-o', 'pipefail', '-c', CLIS[kind].install], INSTALL_MS, true, signal);
217
- return ran.status === 0 ? null : failureOf(ran, 'the install');
205
+ async function bounded(program, work, signal) {
206
+ const deadline = AbortSignal.timeout(INSTALL_MS);
207
+ const ran = await work(signal === undefined ? deadline : AbortSignal.any([signal, deadline]));
208
+ if (deadline.aborted && signal?.aborted !== true)
209
+ return `${program} did not end within ${INSTALL_MS / 1000} seconds`;
210
+ return ran.status === 0 ? null : failureOf(ran, program);
211
+ }
212
+ export function installCli(kind, signal) {
213
+ return bounded('the install', (within) => run('bash', ['-o', 'pipefail', '-c', CLIS[kind].install], INSTALL_MS, true, within), signal);
218
214
  }
219
215
  function loginShell() {
220
216
  return process.env.SHELL || userInfo().shell;
@@ -222,13 +218,19 @@ function loginShell() {
222
218
  const FOUND = 'house-kit-cli ';
223
219
  const LOOKUP = `found=$(command -v "$1") || exit 0; case $found in /*) ;; *) found=$(pwd -P)/$found ;; esac; printf "${FOUND}%s\\n" "$found"`;
224
220
  const USER_BIN = 'case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) PATH="$PATH:$HOME/.local/bin" ;; esac; export PATH';
225
- function inLoginShell(script, argument = '', signal) {
226
- return run(loginShell(), ['-l', '-i', '-c', `exec /bin/sh -c '${USER_BIN}; ${script}' sh ${argument}`], READ_MS, true, signal);
221
+ function inLoginShell(script, argument = '', signal, timeoutMs = READ_MS) {
222
+ return run(loginShell(), ['-l', '-i', '-c', `exec /bin/sh -c '${USER_BIN}; ${script}' sh ${argument}`], timeoutMs, true, signal);
227
223
  }
228
- export async function locate(kind, signal) {
229
- const ran = await inLoginShell(LOOKUP, CLIS[kind].bin, signal);
224
+ export async function onLoginPath(program, signal) {
225
+ const ran = await inLoginShell(LOOKUP, program, signal);
230
226
  return ran.stdout.split('\n').findLast((line) => line.startsWith(FOUND))?.slice(FOUND.length) ?? null;
231
227
  }
228
+ export function locate(kind, signal) {
229
+ return onLoginPath(CLIS[kind].bin, signal);
230
+ }
231
+ export function updateCli(kind) {
232
+ return bounded('the update', (within) => inLoginShell(CLIS[kind].update, '', within, INSTALL_MS));
233
+ }
232
234
  export async function loginPath() {
233
235
  const marker = 'house-kit-path ';
234
236
  const ran = await inLoginShell(`printf "${marker}%s\\n" "$PATH"`);
@@ -1,42 +1,18 @@
1
1
  import { subscribe } from 'node:diagnostics_channel';
2
+ import { setTimeout as delay } from 'node:timers/promises';
2
3
  import { HouseRefusal, retryDelay } from './api.js';
3
4
  import { end, REPLACED, signInAgain } from './end.js';
4
5
  import { readEnrolment } from './home.js';
5
6
  import { relayed } from './relay.js';
6
- import { endUnserved, KIT_WIRE } from './wire.js';
7
+ import { Silence } from './silence.js';
8
+ import { endUnserved, KIT_WIRE, unserved } from './wire.js';
7
9
  const PATH = '/kit/stream';
8
10
  const SUBPROTOCOL = `house.kit.stream.${KIT_WIRE}`;
9
11
  const REFUSAL_HEADER = 'x-house-refusal';
10
12
  // House beats each Kit connection every thirty seconds, so two silent beats mean this Kit process cannot hear House.
11
13
  export const CONNECTION_SILENCE_MS = 60_000;
12
- const SYSTEM_CONNECTION_CLOCK = {
13
- later: (delay, callback) => setTimeout(callback, delay),
14
- clear: (timer) => clearTimeout(timer),
15
- };
16
- export class ConnectionSilence {
17
- timer = null;
18
- silent;
19
- clock;
20
- interval;
21
- constructor(silent, clock = SYSTEM_CONNECTION_CLOCK, interval = CONNECTION_SILENCE_MS) {
22
- this.silent = silent;
23
- this.clock = clock;
24
- this.interval = interval;
25
- }
26
- heard() {
27
- this.stop();
28
- this.timer = this.clock.later(this.interval, () => {
29
- this.timer = null;
30
- this.silent();
31
- });
32
- }
33
- stop() {
34
- if (this.timer === null)
35
- return;
36
- this.clock.clear(this.timer);
37
- this.timer = null;
38
- }
39
- }
14
+ // A stopping Kit waits up to two seconds for House to answer its close, so what it sent last reaches House and a House that does not answer holds no stop.
15
+ const CLOSE_ANSWER_MS = 2_000;
40
16
  function connectionUrl(house) {
41
17
  const url = new URL(PATH, house);
42
18
  url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
@@ -58,22 +34,32 @@ subscribe('undici:request:headers', (message) => {
58
34
  });
59
35
  export function holdConnection(handlers) {
60
36
  let connection = null;
37
+ let socket = null;
61
38
  let failures = 0;
39
+ let stopping = false;
62
40
  const connect = async () => {
63
41
  const { house, credential } = (await readEnrolment());
42
+ if (socket !== null || unserved() || stopping)
43
+ return;
64
44
  refused = null;
65
45
  const opening = new WebSocket(relayed(connectionUrl(house)), {
66
46
  protocols: [SUBPROTOCOL],
67
47
  headers: { authorization: `Bearer ${credential}` },
68
48
  });
49
+ socket = opening;
69
50
  let opened = false;
70
51
  let silence = null;
71
52
  const closed = (event) => {
72
53
  silence?.stop();
73
54
  silence = null;
55
+ if (socket === opening)
56
+ socket = null;
74
57
  if (connection === opening)
75
58
  connection = null;
59
+ handlers.closed();
76
60
  process.stderr.write(`kit: connection closed ${event.code} ${event.reason}\n`);
61
+ if (stopping)
62
+ return;
77
63
  if (event.reason === 'replaced')
78
64
  end(REPLACED);
79
65
  if (event.reason === 'credential_rejected' || refused?.status === 401) {
@@ -91,7 +77,7 @@ export function holdConnection(handlers) {
91
77
  opened = true;
92
78
  failures = 0;
93
79
  connection = opening;
94
- silence = new ConnectionSilence(() => {
80
+ silence = new Silence(CONNECTION_SILENCE_MS, () => {
95
81
  if (connection !== opening)
96
82
  return;
97
83
  connection = null;
@@ -108,18 +94,27 @@ export function holdConnection(handlers) {
108
94
  if (arrived.type === 'input')
109
95
  handlers.call(arrived);
110
96
  else if (arrived.type !== 'beat')
111
- handlers.notification(arrived);
97
+ handlers.oneWayCall(arrived);
112
98
  };
113
99
  opening.onerror = () => undefined;
114
100
  opening.onclose = closed;
115
101
  };
116
102
  void connect();
117
103
  return {
118
- send(notification) {
104
+ send(oneWayCall) {
119
105
  if (connection === null || connection.readyState !== WebSocket.OPEN)
120
106
  return false;
121
- connection.send(JSON.stringify(notification));
107
+ connection.send(JSON.stringify(oneWayCall));
122
108
  return true;
123
109
  },
110
+ close() {
111
+ stopping = true;
112
+ const open = socket;
113
+ if (open === null)
114
+ return Promise.resolve();
115
+ const answered = new Promise((resolve) => open.addEventListener('close', () => resolve(), { once: true }));
116
+ open.close();
117
+ return Promise.race([answered, delay(CLOSE_ANSWER_MS)]);
118
+ },
124
119
  };
125
120
  }
@@ -0,0 +1,63 @@
1
+ import { applied } from '@agentshouse/session-content';
2
+ function whole(part, parent) {
3
+ return { ...part, parent };
4
+ }
5
+ export class Content {
6
+ parts = [];
7
+ emit;
8
+ keys = new Map();
9
+ writing = new Map();
10
+ planned = null;
11
+ constructor(emit) {
12
+ this.emit = emit;
13
+ }
14
+ index(key) {
15
+ return this.keys.get(key);
16
+ }
17
+ write(type, id, parent, text) {
18
+ if (text === '')
19
+ return;
20
+ const writing = this.writing.get(parent);
21
+ if (writing?.type === type && writing.id === id) {
22
+ this.apply({ op: 'append', index: writing.index, text });
23
+ return;
24
+ }
25
+ const index = this.add(parent, { type, text });
26
+ this.writing.set(parent, { type, id, index });
27
+ }
28
+ put(key, parent, part) {
29
+ const index = this.keys.get(key);
30
+ if (index === undefined) {
31
+ const added = this.add(parent, part);
32
+ this.keys.set(key, added);
33
+ return added;
34
+ }
35
+ const changed = whole(part, this.parts[index].parent);
36
+ if (JSON.stringify(changed) !== JSON.stringify(this.parts[index]))
37
+ this.apply({ op: 'set', index, part: changed });
38
+ return index;
39
+ }
40
+ plan(entries) {
41
+ if (this.planned === null) {
42
+ this.planned = this.add(null, { type: 'plan', entries });
43
+ return;
44
+ }
45
+ this.apply({ op: 'set', index: this.planned, part: { type: 'plan', parent: null, entries } });
46
+ }
47
+ add(parent, part) {
48
+ this.writing.delete(parent);
49
+ return this.arrived(parent, part);
50
+ }
51
+ arrived(parent, part) {
52
+ const index = this.parts.length;
53
+ this.apply({ op: 'start', index, part: whole(part, parent) });
54
+ return index;
55
+ }
56
+ operations() {
57
+ return this.parts.map((part, index) => ({ op: 'start', index, part }));
58
+ }
59
+ apply(operation) {
60
+ this.parts = applied(this.parts, operation);
61
+ this.emit(operation);
62
+ }
63
+ }