amalgm 0.1.79 → 0.1.80

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 (30) hide show
  1. package/package.json +1 -1
  2. package/runtime/lib/chatInput.js +0 -4
  3. package/runtime/scripts/amalgm-mcp/agent-config/compiler/instructions.js +70 -0
  4. package/runtime/scripts/amalgm-mcp/agent-config/loadout.js +65 -0
  5. package/runtime/scripts/amalgm-mcp/agent-config/renderers/instructions.js +9 -49
  6. package/runtime/scripts/amalgm-mcp/agent-config/rest.js +10 -10
  7. package/runtime/scripts/amalgm-mcp/agent-config/schema.js +15 -31
  8. package/runtime/scripts/amalgm-mcp/agent-config/store.js +21 -5
  9. package/runtime/scripts/amalgm-mcp/agents/rest.js +34 -34
  10. package/runtime/scripts/amalgm-mcp/agents/store.js +19 -28
  11. package/runtime/scripts/amalgm-mcp/agents/talk.js +10 -12
  12. package/runtime/scripts/amalgm-mcp/agents/tools.js +1 -1
  13. package/runtime/scripts/amalgm-mcp/automations/runner.js +1 -6
  14. package/runtime/scripts/amalgm-mcp/email/inbound.js +12 -8
  15. package/runtime/scripts/amalgm-mcp/mcp-connections/rest.js +0 -13
  16. package/runtime/scripts/amalgm-mcp/server/mcp-request-context.js +5 -0
  17. package/runtime/scripts/amalgm-mcp/slack/inbound.js +12 -8
  18. package/runtime/scripts/amalgm-mcp/tests/agent-config.test.js +1 -1
  19. package/runtime/scripts/amalgm-mcp/tests/agents-source-of-truth.test.js +3 -5
  20. package/runtime/scripts/amalgm-mcp/tests/chat-payloads.test.js +1 -1
  21. package/runtime/scripts/amalgm-mcp/tests/mcp-surface.test.js +2 -12
  22. package/runtime/scripts/amalgm-mcp/tests/toolbox-service.test.js +3 -4
  23. package/runtime/scripts/amalgm-mcp/toolbox/loadout-context.js +57 -0
  24. package/runtime/scripts/amalgm-mcp/toolbox/mcp-surface.js +8 -8
  25. package/runtime/scripts/amalgm-mcp/toolbox/service.js +17 -13
  26. package/runtime/scripts/amalgm-mcp/workflows/runner.js +1 -6
  27. package/runtime/scripts/chat-core/chat-payload.js +165 -0
  28. package/runtime/scripts/chat-core/server.js +4 -2
  29. package/runtime/scripts/chat-core/tests/chat-payload.test.js +78 -0
  30. package/runtime/scripts/amalgm-mcp/toolbox/selection.js +0 -42
@@ -0,0 +1,165 @@
1
+ 'use strict';
2
+
3
+ const { chatInputToLegacyFields, normalizeChatInput } = require('../../lib/chatInput');
4
+ const { getChatPayload } = require('../amalgm-mcp/lib/chat-payloads');
5
+ const { buildLocalMcpServerConfigs } = require('../amalgm-mcp/lib/mcp-resolver');
6
+ const { normalizeLoadout } = require('../amalgm-mcp/agent-config/loadout');
7
+
8
+ function isObject(value) {
9
+ return !!value && typeof value === 'object' && !Array.isArray(value);
10
+ }
11
+
12
+ function nullableString(value) {
13
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
14
+ }
15
+
16
+ function uniqueStrings(value) {
17
+ if (!Array.isArray(value)) return [];
18
+ return [...new Set(value
19
+ .filter((item) => typeof item === 'string')
20
+ .map((item) => item.trim())
21
+ .filter(Boolean))];
22
+ }
23
+
24
+ function harnessToAgent(harness) {
25
+ if (harness === 'codex') return 'codex';
26
+ if (harness === 'opencode') return 'opencode';
27
+ return 'claude';
28
+ }
29
+
30
+ function applyPayloadRecord(body, record) {
31
+ const payload = isObject(record?.payload) ? record.payload : {};
32
+ const rawChatInput = isObject(body.chatInput) ? body.chatInput : {};
33
+ const rawAgent = isObject(rawChatInput.agent) ? rawChatInput.agent : {};
34
+ const rawTools = isObject(rawChatInput.tools) ? rawChatInput.tools : {};
35
+ const rawExecution = isObject(rawChatInput.execution) ? rawChatInput.execution : {};
36
+ const modelSettings = isObject(payload.modelSettings)
37
+ ? payload.modelSettings
38
+ : isObject(body.modelSettings)
39
+ ? body.modelSettings
40
+ : {};
41
+ const harness =
42
+ nullableString(payload.resolvedHarnessId)
43
+ || nullableString(payload.harness)
44
+ || nullableString(rawAgent.harness)
45
+ || nullableString(body.harness)
46
+ || 'claude_code';
47
+ const modelId =
48
+ nullableString(payload.modelId)
49
+ || nullableString(rawAgent.model)
50
+ || nullableString(body.modelId)
51
+ || nullableString(body.model);
52
+ const authMethod =
53
+ nullableString(payload.authMethod)
54
+ || nullableString(rawAgent.authMethod)
55
+ || nullableString(body.authMethod);
56
+ const customAgentId =
57
+ nullableString(payload.customAgentId)
58
+ || nullableString(rawAgent.customAgentId);
59
+ const systemPrompt =
60
+ nullableString(payload.systemPrompt)
61
+ || nullableString(rawAgent.systemPrompt)
62
+ || nullableString(body.systemPrompt);
63
+ const cwd =
64
+ nullableString(body.cwd)
65
+ || nullableString(rawExecution.cwd)
66
+ || nullableString(payload.cwd);
67
+ const computerId =
68
+ nullableString(payload.machineId)
69
+ || nullableString(body.computerId)
70
+ || nullableString(rawExecution.computerId)
71
+ || nullableString(process.env.AMALGM_COMPUTER_ID)
72
+ || nullableString(process.env.AMALGM_CONTAINER_ID);
73
+ const mcpAppIds = uniqueStrings(payload.mcpAppIds);
74
+ const toolIds = normalizeLoadout(payload.loadout || payload.tools).toolIds;
75
+ const chatInput = normalizeChatInput({
76
+ ...rawChatInput,
77
+ agent: {
78
+ ...rawAgent,
79
+ harness,
80
+ ...(modelId ? { model: modelId } : {}),
81
+ ...(authMethod ? { authMethod } : {}),
82
+ customAgentId,
83
+ systemPrompt,
84
+ },
85
+ tools: {
86
+ ...rawTools,
87
+ mcpAppIds,
88
+ toolIds,
89
+ },
90
+ execution: {
91
+ ...rawExecution,
92
+ cwd,
93
+ computerId,
94
+ },
95
+ }, {
96
+ prompt: body.prompt,
97
+ userParts: body.userParts,
98
+ harness,
99
+ modelId,
100
+ authMethod,
101
+ cwd,
102
+ computerId,
103
+ mcpAppIds,
104
+ systemPrompt,
105
+ });
106
+ const legacy = chatInputToLegacyFields(chatInput, { prompt: body.prompt });
107
+ const reasoningEffort =
108
+ nullableString(modelSettings.effort)
109
+ || nullableString(modelSettings.reasoningEffort)
110
+ || nullableString(modelSettings.reasoning);
111
+
112
+ const next = {
113
+ ...body,
114
+ chatInput,
115
+ ...legacy,
116
+ harness,
117
+ ...(modelId ? { modelId, model: modelId } : {}),
118
+ ...(authMethod ? { authMethod } : {}),
119
+ ...(systemPrompt ? { systemPrompt } : {}),
120
+ ...(cwd ? { cwd, projectPath: cwd } : {}),
121
+ ...(computerId ? { computerId } : {}),
122
+ mcpAppIds,
123
+ modelSettings,
124
+ agentId: customAgentId || harnessToAgent(harness),
125
+ ...(customAgentId ? { agentConfigId: customAgentId } : {}),
126
+ ...(reasoningEffort ? { reasoningEffort } : {}),
127
+ ...(modelSettings.fastMode === true ? { fastMode: true } : {}),
128
+ };
129
+
130
+ delete next.cliModel;
131
+ delete next.internalModelId;
132
+ delete next.contextWindow;
133
+ delete next.maxTokens;
134
+ return next;
135
+ }
136
+
137
+ async function resolveMachineChatPayload(body) {
138
+ const payloadId = nullableString(body?.chatPayloadId);
139
+ if (!payloadId) return body;
140
+
141
+ const record = getChatPayload(payloadId);
142
+ if (!record || !isObject(record.payload)) {
143
+ throw Object.assign(new Error(`Chat payload not found: ${payloadId}`), { status: 404 });
144
+ }
145
+
146
+ const expectedRevision = nullableString(body.chatPayloadRevision);
147
+ const actualRevision = nullableString(record.revision);
148
+ if (expectedRevision && actualRevision && expectedRevision !== actualRevision) {
149
+ throw Object.assign(
150
+ new Error('Chat payload changed before launch; retry with the latest machine payload.'),
151
+ { status: 409 },
152
+ );
153
+ }
154
+
155
+ const resolved = applyPayloadRecord(body, record);
156
+ return {
157
+ ...resolved,
158
+ mcpServers: await buildLocalMcpServerConfigs(resolved.mcpAppIds || []),
159
+ };
160
+ }
161
+
162
+ module.exports = {
163
+ applyPayloadRecord,
164
+ resolveMachineChatPayload,
165
+ };
@@ -12,6 +12,7 @@ const { forwardMcpRelay, parseMcpRelayPath } = require('./tooling/mcp-relay');
12
12
  const { RuntimeController } = require('./runtime');
13
13
  const { writeChatStream, writeRawTempStream } = require('./streams');
14
14
  const { TurnStore } = require('./stores');
15
+ const { resolveMachineChatPayload } = require('./chat-payload');
15
16
  const { authorizeRuntimeHttp } = require('../runtime-auth');
16
17
 
17
18
  function readBody(req) {
@@ -108,12 +109,13 @@ function createServer(core = createCore()) {
108
109
  }
109
110
  if (route.handler === 'chat') {
110
111
  if (req.method !== 'POST') return sendJson(res, 405, { error: 'Method not allowed' });
111
- const payload = await readBody(req);
112
+ const payload = await resolveMachineChatPayload(await readBody(req));
112
113
  return await writeChatStream(core, payload, res);
113
114
  }
114
115
  } catch (err) {
115
116
  console.error('[ChatCore] error:', err);
116
- if (!res.headersSent) sendJson(res, 500, { error: err.message || 'Internal server error' });
117
+ const status = Number.isInteger(err?.status) ? err.status : 500;
118
+ if (!res.headersSent) sendJson(res, status, { error: err.message || 'Internal server error' });
117
119
  else {
118
120
  res.write(`data: ${JSON.stringify({ _type: 'error', message: err.message || 'Internal server error' })}\n\n`);
119
121
  res.write(`data: ${JSON.stringify({ _type: 'complete', stopReason: 'error' })}\n\n`);
@@ -0,0 +1,78 @@
1
+ 'use strict';
2
+
3
+ const test = require('node:test');
4
+ const assert = require('node:assert/strict');
5
+ const fs = require('fs');
6
+ const os = require('os');
7
+ const path = require('path');
8
+
9
+ const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'amalgm-chat-core-payload-test-'));
10
+ process.env.AMALGM_DIR = path.join(tempRoot, '.amalgm');
11
+ process.env.AMALGM_COMPUTER_ID = 'machine-local';
12
+
13
+ const { closeLocalDb } = require('../../amalgm-mcp/state/db');
14
+ const { writeChatPayload } = require('../../amalgm-mcp/lib/chat-payloads');
15
+ const { resolveMachineChatPayload } = require('../chat-payload');
16
+
17
+ test.after(() => {
18
+ closeLocalDb();
19
+ fs.rmSync(tempRoot, { recursive: true, force: true });
20
+ });
21
+
22
+ test('chat-core resolves launch payload from the local machine cache', async () => {
23
+ writeChatPayload({
24
+ id: 'chat-view:test',
25
+ revision: 'rev-1',
26
+ payload: {
27
+ machineId: 'machine-local',
28
+ harness: 'codex',
29
+ resolvedHarnessId: 'codex',
30
+ modelId: 'openai/gpt-5.5',
31
+ modelSettings: { effort: 'high', fastMode: true },
32
+ authMethod: 'amalgm',
33
+ cwd: '/tmp/amalgm-project',
34
+ customAgentId: null,
35
+ systemPrompt: 'local payload prompt',
36
+ mcpAppIds: [],
37
+ loadout: { toolIds: ['tool.search'] },
38
+ pendingWorktree: false,
39
+ },
40
+ });
41
+
42
+ const resolved = await resolveMachineChatPayload({
43
+ chatPayloadId: 'chat-view:test',
44
+ chatPayloadRevision: 'rev-1',
45
+ prompt: 'hello',
46
+ chatInput: {
47
+ parts: [{ type: 'text', text: 'hello' }],
48
+ agent: {},
49
+ tools: {},
50
+ execution: {},
51
+ },
52
+ });
53
+
54
+ assert.equal(resolved.harness, 'codex');
55
+ assert.equal(resolved.modelId, 'openai/gpt-5.5');
56
+ assert.equal(resolved.authMethod, 'amalgm');
57
+ assert.equal(resolved.cwd, '/tmp/amalgm-project');
58
+ assert.equal(resolved.computerId, 'machine-local');
59
+ assert.equal(resolved.reasoningEffort, 'high');
60
+ assert.equal(resolved.fastMode, true);
61
+ assert.deepEqual(resolved.chatInput.tools.toolIds, ['tool.search']);
62
+ assert.deepEqual(resolved.mcpServers, []);
63
+ assert.equal(resolved.cliModel, undefined);
64
+ });
65
+
66
+ test('chat-core rejects stale chat payload revisions', async () => {
67
+ await assert.rejects(
68
+ () => resolveMachineChatPayload({
69
+ chatPayloadId: 'chat-view:test',
70
+ chatPayloadRevision: 'rev-stale',
71
+ prompt: 'hello',
72
+ }),
73
+ (error) => {
74
+ assert.equal(error.status, 409);
75
+ return true;
76
+ },
77
+ );
78
+ });
@@ -1,42 +0,0 @@
1
- 'use strict';
2
-
3
- const FIRST_PARTY_TOOL_IDS = new Set([
4
- 'automations',
5
- 'notifications',
6
- 'agents',
7
- 'apps',
8
- 'browser',
9
- ]);
10
-
11
- function selectedToolIdsForContext(context) {
12
- const tools = context?.sessionMetadata?.tools;
13
- if (!tools || tools.mode !== 'selected') return null;
14
- const selected = Array.isArray(tools.selectedToolIds)
15
- ? tools.selectedToolIds
16
- : Array.isArray(tools.selected)
17
- ? tools.selected
18
- : [];
19
- return new Set(selected.map((value) => String(value || '').trim()).filter(Boolean));
20
- }
21
-
22
- function selectedHas(selectedToolIds, id) {
23
- if (!id) return false;
24
- if (selectedToolIds.has(id)) return true;
25
- const value = String(id || '').trim();
26
- const toolId = value.split('.')[0];
27
- if (FIRST_PARTY_TOOL_IDS.has(toolId) && selectedToolIds.has(`amalgm.${value}`)) return true;
28
- if (value === 'notifications.notify_user' && selectedToolIds.has('amalgm.notify_user')) return true;
29
- if (value === 'agents.talk_to_agent' && selectedToolIds.has('amalgm.talk_to_agent')) return true;
30
- if (FIRST_PARTY_TOOL_IDS.has(value) && selectedToolIds.has(`amalgm.${value}`)) return true;
31
- return false;
32
- }
33
-
34
- function selectedContainsToolOrAction(selectedToolIds, toolId, actionId) {
35
- if (!selectedToolIds) return true;
36
- return selectedHas(selectedToolIds, toolId) || selectedHas(selectedToolIds, actionId);
37
- }
38
-
39
- module.exports = {
40
- selectedContainsToolOrAction,
41
- selectedToolIdsForContext,
42
- };