@geminixiang/mikan 1.0.0-beta.39 → 1.0.0-beta.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/README.md +50 -23
- package/dist/adapter.d.ts +1 -1
- package/dist/adapter.d.ts.map +1 -1
- package/dist/adapter.js.map +1 -1
- package/dist/adapters/discord/bot.d.ts +2 -1
- package/dist/adapters/discord/bot.d.ts.map +1 -1
- package/dist/adapters/discord/bot.js +3 -3
- package/dist/adapters/discord/bot.js.map +1 -1
- package/dist/adapters/discord/context.d.ts +2 -1
- package/dist/adapters/discord/context.d.ts.map +1 -1
- package/dist/adapters/discord/context.js +1 -1
- package/dist/adapters/discord/context.js.map +1 -1
- package/dist/adapters/github/bot.d.ts +2 -1
- package/dist/adapters/github/bot.d.ts.map +1 -1
- package/dist/adapters/github/bot.js +11 -7
- package/dist/adapters/github/bot.js.map +1 -1
- package/dist/adapters/github/client.js +2 -2
- package/dist/adapters/github/client.js.map +1 -1
- package/dist/adapters/github/context.d.ts +4 -2
- package/dist/adapters/github/context.d.ts.map +1 -1
- package/dist/adapters/github/context.js +2 -2
- package/dist/adapters/github/context.js.map +1 -1
- package/dist/adapters/github/gcp-auth.js +2 -2
- package/dist/adapters/github/gcp-auth.js.map +1 -1
- package/dist/adapters/github/github-ops.d.ts +3 -2
- package/dist/adapters/github/github-ops.d.ts.map +1 -1
- package/dist/adapters/github/github-ops.js +1 -1
- package/dist/adapters/github/github-ops.js.map +1 -1
- package/dist/adapters/github/ids.d.ts.map +1 -1
- package/dist/adapters/github/ids.js +7 -3
- package/dist/adapters/github/ids.js.map +1 -1
- package/dist/adapters/github/repo.js +3 -3
- package/dist/adapters/github/repo.js.map +1 -1
- package/dist/adapters/github/types.d.ts +2 -1
- package/dist/adapters/github/types.d.ts.map +1 -1
- package/dist/adapters/github/types.js.map +1 -1
- package/dist/adapters/progressive-renderer.js +1 -1
- package/dist/adapters/progressive-renderer.js.map +1 -1
- package/dist/adapters/shared.js +4 -4
- package/dist/adapters/shared.js.map +1 -1
- package/dist/adapters/slack/blocks.d.ts.map +1 -1
- package/dist/adapters/slack/blocks.js +3 -1
- package/dist/adapters/slack/blocks.js.map +1 -1
- package/dist/adapters/slack/bot.d.ts +12 -2
- package/dist/adapters/slack/bot.d.ts.map +1 -1
- package/dist/adapters/slack/bot.js +70 -9
- package/dist/adapters/slack/bot.js.map +1 -1
- package/dist/adapters/slack/context.d.ts +2 -1
- package/dist/adapters/slack/context.d.ts.map +1 -1
- package/dist/adapters/slack/context.js +1 -0
- package/dist/adapters/slack/context.js.map +1 -1
- package/dist/adapters/slack/response-lifecycle.d.ts.map +1 -1
- package/dist/adapters/slack/response-lifecycle.js +4 -4
- package/dist/adapters/slack/response-lifecycle.js.map +1 -1
- package/dist/adapters/slack/session.d.ts.map +1 -1
- package/dist/adapters/slack/session.js +2 -3
- package/dist/adapters/slack/session.js.map +1 -1
- package/dist/adapters/slack/tools/attach.js +1 -1
- package/dist/adapters/slack/tools/attach.js.map +1 -1
- package/dist/adapters/telegram/bot.d.ts +2 -1
- package/dist/adapters/telegram/bot.d.ts.map +1 -1
- package/dist/adapters/telegram/bot.js +6 -6
- package/dist/adapters/telegram/bot.js.map +1 -1
- package/dist/adapters/telegram/context.d.ts +2 -1
- package/dist/adapters/telegram/context.d.ts.map +1 -1
- package/dist/adapters/telegram/context.js.map +1 -1
- package/dist/adapters/telegram/html.d.ts.map +1 -1
- package/dist/adapters/telegram/html.js +10 -7
- package/dist/adapters/telegram/html.js.map +1 -1
- package/dist/adapters/types.d.ts +4 -2
- package/dist/adapters/types.d.ts.map +1 -1
- package/dist/adapters/types.js.map +1 -1
- package/dist/agent-events.d.ts +3 -2
- package/dist/agent-events.d.ts.map +1 -1
- package/dist/agent-events.js +19 -1
- package/dist/agent-events.js.map +1 -1
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +34 -9
- package/dist/agent.js.map +1 -1
- package/dist/cli/arg-grammar.d.ts.map +1 -1
- package/dist/cli/arg-grammar.js +5 -3
- package/dist/cli/arg-grammar.js.map +1 -1
- package/dist/cli/boot.d.ts.map +1 -1
- package/dist/cli/boot.js +5 -3
- package/dist/cli/boot.js.map +1 -1
- package/dist/cli/download.d.ts.map +1 -1
- package/dist/cli/download.js +2 -0
- package/dist/cli/download.js.map +1 -1
- package/dist/cli/ext-dev.d.ts.map +1 -1
- package/dist/cli/ext-dev.js +4 -1
- package/dist/cli/ext-dev.js.map +1 -1
- package/dist/cli/ext.d.ts.map +1 -1
- package/dist/cli/ext.js +123 -23
- package/dist/cli/ext.js.map +1 -1
- package/dist/cli/office.d.ts.map +1 -1
- package/dist/cli/office.js +2 -0
- package/dist/cli/office.js.map +1 -1
- package/dist/cli/types.d.ts +0 -6
- package/dist/cli/types.d.ts.map +1 -1
- package/dist/cli/types.js.map +1 -1
- package/dist/commands/admin.js +1 -1
- package/dist/commands/admin.js.map +1 -1
- package/dist/commands/auto-reply.js +2 -2
- package/dist/commands/auto-reply.js.map +1 -1
- package/dist/commands/extensions.js +1 -1
- package/dist/commands/extensions.js.map +1 -1
- package/dist/commands/login.js +1 -1
- package/dist/commands/login.js.map +1 -1
- package/dist/commands/manifest.d.ts +7 -0
- package/dist/commands/manifest.d.ts.map +1 -1
- package/dist/commands/manifest.js +28 -0
- package/dist/commands/manifest.js.map +1 -1
- package/dist/commands/model.d.ts.map +1 -1
- package/dist/commands/model.js +4 -1
- package/dist/commands/model.js.map +1 -1
- package/dist/commands/new.js +1 -1
- package/dist/commands/new.js.map +1 -1
- package/dist/commands/sandbox.js +3 -3
- package/dist/commands/sandbox.js.map +1 -1
- package/dist/commands/session-view.d.ts.map +1 -1
- package/dist/commands/session-view.js +5 -2
- package/dist/commands/session-view.js.map +1 -1
- package/dist/commands/types.d.ts +1 -1
- package/dist/commands/types.d.ts.map +1 -1
- package/dist/commands/types.js.map +1 -1
- package/dist/config.js +4 -4
- package/dist/config.js.map +1 -1
- package/dist/env-manifest.d.ts +2 -0
- package/dist/env-manifest.d.ts.map +1 -1
- package/dist/env-manifest.js +11 -1
- package/dist/env-manifest.js.map +1 -1
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +7 -6
- package/dist/events.js.map +1 -1
- package/dist/execution-resolver.d.ts.map +1 -1
- package/dist/execution-resolver.js +3 -2
- package/dist/execution-resolver.js.map +1 -1
- package/dist/extension-schedules.d.ts +31 -0
- package/dist/extension-schedules.d.ts.map +1 -0
- package/dist/extension-schedules.js +229 -0
- package/dist/extension-schedules.js.map +1 -0
- package/dist/harness/auth.js +5 -5
- package/dist/harness/auth.js.map +1 -1
- package/dist/harness/event-format.d.ts +2 -0
- package/dist/harness/event-format.d.ts.map +1 -1
- package/dist/harness/event-format.js +2 -1
- package/dist/harness/event-format.js.map +1 -1
- package/dist/harness/extensions/loader.d.ts +2 -2
- package/dist/harness/extensions/loader.d.ts.map +1 -1
- package/dist/harness/extensions/loader.js +135 -33
- package/dist/harness/extensions/loader.js.map +1 -1
- package/dist/harness/extensions/registry.d.ts +33 -1
- package/dist/harness/extensions/registry.d.ts.map +1 -1
- package/dist/harness/extensions/registry.js +79 -2
- package/dist/harness/extensions/registry.js.map +1 -1
- package/dist/harness/extensions/types.d.ts +165 -21
- package/dist/harness/extensions/types.d.ts.map +1 -1
- package/dist/harness/extensions/types.js.map +1 -1
- package/dist/harness/index.d.ts +2 -2
- package/dist/harness/index.d.ts.map +1 -1
- package/dist/harness/index.js +1 -1
- package/dist/harness/index.js.map +1 -1
- package/dist/harness/models.d.ts.map +1 -1
- package/dist/harness/models.js +36 -24
- package/dist/harness/models.js.map +1 -1
- package/dist/harness/runner.js +2 -2
- package/dist/harness/runner.js.map +1 -1
- package/dist/harness/session-store.d.ts.map +1 -1
- package/dist/harness/session-store.js +9 -7
- package/dist/harness/session-store.js.map +1 -1
- package/dist/harness/skills.js +3 -3
- package/dist/harness/skills.js.map +1 -1
- package/dist/harness/subagent-profiles.js +2 -2
- package/dist/harness/subagent-profiles.js.map +1 -1
- package/dist/harness/subagent-runner.js +3 -3
- package/dist/harness/subagent-runner.js.map +1 -1
- package/dist/index.d.ts +8 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/dist/main.js +58 -9
- package/dist/main.js.map +1 -1
- package/dist/observability/instrument.js +1 -1
- package/dist/observability/instrument.js.map +1 -1
- package/dist/observability/sentry.js +1 -1
- package/dist/observability/sentry.js.map +1 -1
- package/dist/office/index.d.ts +1 -1
- package/dist/office/index.d.ts.map +1 -1
- package/dist/office/index.js +1 -1
- package/dist/office/index.js.map +1 -1
- package/dist/office/layout.d.ts +7 -0
- package/dist/office/layout.d.ts.map +1 -1
- package/dist/office/layout.js +10 -1
- package/dist/office/layout.js.map +1 -1
- package/dist/office/registry.d.ts.map +1 -1
- package/dist/office/registry.js +7 -5
- package/dist/office/registry.js.map +1 -1
- package/dist/packages/materialize.js +10 -3
- package/dist/packages/materialize.js.map +1 -1
- package/dist/packages/source.d.ts +6 -0
- package/dist/packages/source.d.ts.map +1 -1
- package/dist/packages/source.js +14 -2
- package/dist/packages/source.js.map +1 -1
- package/dist/packages/types.d.ts +5 -3
- package/dist/packages/types.d.ts.map +1 -1
- package/dist/packages/types.js.map +1 -1
- package/dist/provisioner.js +5 -5
- package/dist/provisioner.js.map +1 -1
- package/dist/runtime/conversation-runtime.d.ts.map +1 -1
- package/dist/runtime/conversation-runtime.js +44 -2
- package/dist/runtime/conversation-runtime.js.map +1 -1
- package/dist/runtime/types.d.ts +10 -2
- package/dist/runtime/types.d.ts.map +1 -1
- package/dist/runtime/types.js.map +1 -1
- package/dist/sandbox/cloudflare.js +1 -1
- package/dist/sandbox/cloudflare.js.map +1 -1
- package/dist/sandbox/container.js +1 -2
- package/dist/sandbox/container.js.map +1 -1
- package/dist/sandbox/firecracker.js +1 -1
- package/dist/sandbox/firecracker.js.map +1 -1
- package/dist/sandbox/gondolin.d.ts.map +1 -1
- package/dist/sandbox/gondolin.js +1 -2
- package/dist/sandbox/gondolin.js.map +1 -1
- package/dist/sandbox/host.d.ts.map +1 -1
- package/dist/sandbox/host.js +4 -5
- package/dist/sandbox/host.js.map +1 -1
- package/dist/sandbox/index.js +1 -1
- package/dist/sandbox/index.js.map +1 -1
- package/dist/sandbox/utils.d.ts +2 -0
- package/dist/sandbox/utils.d.ts.map +1 -1
- package/dist/sandbox/utils.js +30 -1
- package/dist/sandbox/utils.js.map +1 -1
- package/dist/sessions/chat-history-sync.d.ts.map +1 -1
- package/dist/sessions/chat-history-sync.js +9 -8
- package/dist/sessions/chat-history-sync.js.map +1 -1
- package/dist/sessions/conversation-log.d.ts.map +1 -1
- package/dist/sessions/conversation-log.js +5 -2
- package/dist/sessions/conversation-log.js.map +1 -1
- package/dist/sessions/history-line.d.ts +9 -0
- package/dist/sessions/history-line.d.ts.map +1 -1
- package/dist/sessions/history-line.js +22 -1
- package/dist/sessions/history-line.js.map +1 -1
- package/dist/sessions/session-key.d.ts +5 -12
- package/dist/sessions/session-key.d.ts.map +1 -1
- package/dist/sessions/session-key.js +23 -0
- package/dist/sessions/session-key.js.map +1 -1
- package/dist/sessions/store.d.ts +2 -6
- package/dist/sessions/store.d.ts.map +1 -1
- package/dist/sessions/store.js +16 -16
- package/dist/sessions/store.js.map +1 -1
- package/dist/sessions/types.d.ts +2 -1
- package/dist/sessions/types.d.ts.map +1 -1
- package/dist/sessions/types.js.map +1 -1
- package/dist/tools/bash.js +1 -1
- package/dist/tools/bash.js.map +1 -1
- package/dist/tools/edit.d.ts.map +1 -1
- package/dist/tools/edit.js +4 -1
- package/dist/tools/edit.js.map +1 -1
- package/dist/tools/event.js +1 -1
- package/dist/tools/event.js.map +1 -1
- package/dist/tools/generate-image.js +3 -3
- package/dist/tools/generate-image.js.map +1 -1
- package/dist/tools/read.js +4 -4
- package/dist/tools/read.js.map +1 -1
- package/dist/tools/subagent.d.ts.map +1 -1
- package/dist/tools/subagent.js +9 -2
- package/dist/tools/subagent.js.map +1 -1
- package/dist/tools/types.d.ts +0 -26
- package/dist/tools/types.d.ts.map +1 -1
- package/dist/tools/types.js.map +1 -1
- package/dist/trigger.d.ts +2 -1
- package/dist/trigger.d.ts.map +1 -1
- package/dist/trigger.js.map +1 -1
- package/dist/types.d.ts +108 -16
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +2 -2
- package/dist/types.js.map +1 -1
- package/dist/utils/file-guards.d.ts +9 -0
- package/dist/utils/file-guards.d.ts.map +1 -1
- package/dist/utils/file-guards.js +44 -1
- package/dist/utils/file-guards.js.map +1 -1
- package/dist/vault/disabled.d.ts.map +1 -1
- package/dist/vault/disabled.js +3 -0
- package/dist/vault/disabled.js.map +1 -1
- package/dist/vault/index.d.ts +29 -0
- package/dist/vault/index.d.ts.map +1 -1
- package/dist/vault/index.js +68 -4
- package/dist/vault/index.js.map +1 -1
- package/dist/vault/types.d.ts +2 -0
- package/dist/vault/types.d.ts.map +1 -1
- package/dist/vault/types.js.map +1 -1
- package/dist/web/admin/portal.d.ts +1 -1
- package/dist/web/admin/portal.d.ts.map +1 -1
- package/dist/web/admin/portal.js +194 -22
- package/dist/web/admin/portal.js.map +1 -1
- package/dist/web/admin/provider-models.js +1 -1
- package/dist/web/admin/provider-models.js.map +1 -1
- package/dist/web/login/oauth.js +1 -1
- package/dist/web/login/oauth.js.map +1 -1
- package/dist/web/login/portal.d.ts +1 -1
- package/dist/web/login/portal.d.ts.map +1 -1
- package/dist/web/login/portal.js +13 -36
- package/dist/web/login/portal.js.map +1 -1
- package/dist/web/portal-shell.d.ts +17 -0
- package/dist/web/portal-shell.d.ts.map +1 -1
- package/dist/web/portal-shell.js +66 -1
- package/dist/web/portal-shell.js.map +1 -1
- package/dist/web/server.d.ts +3 -2
- package/dist/web/server.d.ts.map +1 -1
- package/dist/web/server.js +3 -3
- package/dist/web/server.js.map +1 -1
- package/dist/web/session-view/portal.d.ts +1 -1
- package/dist/web/session-view/portal.d.ts.map +1 -1
- package/dist/web/session-view/portal.js +10 -12
- package/dist/web/session-view/portal.js.map +1 -1
- package/dist/web/session-view/service.d.ts.map +1 -1
- package/dist/web/session-view/service.js +11 -6
- package/dist/web/session-view/service.js.map +1 -1
- package/dist/web/session-view/types.d.ts +0 -4
- package/dist/web/session-view/types.d.ts.map +1 -1
- package/dist/web/session-view/types.js.map +1 -1
- package/dist/web/token-store.js +1 -1
- package/dist/web/token-store.js.map +1 -1
- package/package.json +8 -17
- package/dist/cli/ext-git.d.ts +0 -17
- package/dist/cli/ext-git.d.ts.map +0 -1
- package/dist/cli/ext-git.js +0 -107
- package/dist/cli/ext-git.js.map +0 -1
- package/dist/commands/parse.d.ts +0 -7
- package/dist/commands/parse.d.ts.map +0 -1
- package/dist/commands/parse.js +0 -14
- package/dist/commands/parse.js.map +0 -1
- package/dist/commands/text.d.ts +0 -2
- package/dist/commands/text.d.ts.map +0 -1
- package/dist/commands/text.js +0 -16
- package/dist/commands/text.js.map +0 -1
- package/dist/harness/extensions/blockkit.d.ts +0 -19
- package/dist/harness/extensions/blockkit.d.ts.map +0 -1
- package/dist/harness/extensions/blockkit.js +0 -42
- package/dist/harness/extensions/blockkit.js.map +0 -1
- package/dist/sandbox/path-context.d.ts +0 -3
- package/dist/sandbox/path-context.d.ts.map +0 -1
- package/dist/sandbox/path-context.js +0 -30
- package/dist/sandbox/path-context.js.map +0 -1
- package/dist/sessions/metadata.d.ts +0 -3
- package/dist/sessions/metadata.d.ts.map +0 -1
- package/dist/sessions/metadata.js +0 -11
- package/dist/sessions/metadata.js.map +0 -1
- package/dist/sessions/policy.d.ts +0 -6
- package/dist/sessions/policy.d.ts.map +0 -1
- package/dist/sessions/policy.js +0 -25
- package/dist/sessions/policy.js.map +0 -1
- package/dist/tools/truncate.d.ts +0 -33
- package/dist/tools/truncate.d.ts.map +0 -1
- package/dist/tools/truncate.js +0 -184
- package/dist/tools/truncate.js.map +0 -1
- package/dist/utils/date.d.ts +0 -10
- package/dist/utils/date.d.ts.map +0 -1
- package/dist/utils/date.js +0 -23
- package/dist/utils/date.js.map +0 -1
- package/dist/utils/env.d.ts +0 -3
- package/dist/utils/env.d.ts.map +0 -1
- package/dist/utils/env.js +0 -12
- package/dist/utils/env.js.map +0 -1
- package/dist/utils/fs-atomic.d.ts +0 -10
- package/dist/utils/fs-atomic.d.ts.map +0 -1
- package/dist/utils/fs-atomic.js +0 -45
- package/dist/utils/fs-atomic.js.map +0 -1
- package/dist/utils/html.d.ts +0 -2
- package/dist/utils/html.d.ts.map +0 -1
- package/dist/utils/html.js +0 -4
- package/dist/utils/html.js.map +0 -1
- package/dist/utils/http-body.d.ts +0 -10
- package/dist/utils/http-body.d.ts.map +0 -1
- package/dist/utils/http-body.js +0 -34
- package/dist/utils/http-body.js.map +0 -1
- package/dist/vault/injection.d.ts +0 -12
- package/dist/vault/injection.d.ts.map +0 -1
- package/dist/vault/injection.js +0 -30
- package/dist/vault/injection.js.map +0 -1
- package/dist/vault/policy.d.ts +0 -20
- package/dist/vault/policy.d.ts.map +0 -1
- package/dist/vault/policy.js +0 -20
- package/dist/vault/policy.js.map +0 -1
- package/dist/web/agent-events/portal.d.ts +0 -3
- package/dist/web/agent-events/portal.d.ts.map +0 -1
- package/dist/web/agent-events/portal.js +0 -19
- package/dist/web/agent-events/portal.js.map +0 -1
- package/dist/web/request.d.ts +0 -3
- package/dist/web/request.d.ts.map +0 -1
- package/dist/web/request.js +0 -13
- package/dist/web/request.js.map +0 -1
- package/dist/web/session-view/command.d.ts +0 -4
- package/dist/web/session-view/command.d.ts.map +0 -1
- package/dist/web/session-view/command.js +0 -10
- package/dist/web/session-view/command.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/sessions/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,IAAI,CAA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AAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,wBAAwB,CAAC,QAAgB;IAChD,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,oBAAoB,CAAC,QAAQ,CAAC,CAAC;QAC3C,IAAI,CAAC,GAAG;YAAE,OAAO,IAAI,CAAC;QACtB,MAAM,SAAS,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QACzD,IAAI,CAAC,SAAS;YAAE,OAAO,IAAI,CAAC;QAC5B,MAAM,KAAK,GAAG,iBAAiB,CAAC,SAAS,CAAC,CAAC;QAC3C,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,GAAG,KAA8C,CAAC;QACzE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,OAAO,SAAS,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAC;QACzE,MAAM,WAAW,GAAG,IAAI,IAAI,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,CAAC;QAClD,OAAO,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IACnE,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { randomUUID } from \"crypto\";\nimport { existsSync, lstatSync, mkdirSync, readdirSync, rmSync } from \"fs\";\nimport { basename, dirname, join, relative, resolve, sep } from \"path\";\nimport { SessionStore } from \"../harness/index.js\";\nimport { isRecord, parseJsonValue, readTextFileIfExists } from \"../utils/file-guards.js\";\nimport { atomicWritePrivateFile } from \"../utils/fs-atomic.js\";\nimport { isPlatformHistorySession } from \"./metadata.js\";\nimport { assertSessionSuffix, threadSuffixOf } from \"./session-key.js\";\nexport type { ResolvedSessionScope, ThreadRootMessage } from \"./types.js\";\n\n/**\n * Returns the shared session directory for a conversation.\n * Channel sessions use a current pointer within this directory.\n * Thread sessions are stored as fixed files within the same directory.\n */\nexport function getChannelSessionDir(channelDir: string): string {\n return join(channelDir, \"sessions\");\n}\n\n/**\n * Resolves the current active session file for a session directory.\n * Reads the \"current\" pointer file; creates a new session if none exists\n * or the pointed-to file is missing.\n */\nexport function resolveSessionFile(sessionDir: string): string {\n const existing = tryResolveCurrentSession(sessionDir);\n if (existing) return existing;\n return createNewSessionFile(sessionDir);\n}\n\n/**\n * Resolve the current active session file for a session directory.\n * Creates a fully initialized persistent session with the provided cwd when none exists.\n */\nexport function resolveManagedSessionFile(sessionDir: string, cwd: string): string {\n const existingPath = getCurrentSessionPath(sessionDir);\n if (existingPath && !isPlatformHistorySession(existingPath)) return existingPath;\n return createManagedSessionFile(sessionDir, cwd);\n}\n\n/**\n * Extracts the short UUID from a session file path.\n * e.g. \"2026-04-05T00-00_7b54cf90.jsonl\" → \"7b54cf90\"\n */\nexport function extractSessionUuid(sessionFile: string): string {\n return basename(sessionFile).replace(\".jsonl\", \"\").split(\"_\").pop()!;\n}\n\n/**\n * Extracts the thread/suffix part of a session key.\n * \"channelId:threadId\" → \"threadId\", \"channelId\" → \"channelId\"\n */\nexport function extractSessionSuffix(sessionKey: string): string {\n return assertSessionSuffix(threadSuffixOf(sessionKey) ?? sessionKey);\n}\n\n/**\n * Resolve one child path and prove it remains inside its owning directory.\n * Identity validation is the first guard; containment is defense in depth for\n * every session path derived from platform-controlled values.\n */\nfunction resolveChildPath(root: string, child: string): string {\n const resolvedRoot = resolve(root);\n const resolvedChild = resolve(resolvedRoot, child);\n const relation = relative(resolvedRoot, resolvedChild);\n if (!relation || relation === \"..\" || relation.startsWith(`..${sep}`)) {\n throw new Error(`Session path escapes its owning directory: ${JSON.stringify(child)}`);\n }\n return resolvedChild;\n}\n\n/**\n * Creates an empty timestamped file and updates the \"current\" pointer.\n * Used only by tests for placeholder-file scenarios.\n *\n * Order matters: write the session file first, then atomic-rename the pointer\n * last so a crash mid-create never leaves \"current\" pointing at a missing file.\n */\nexport function createNewSessionFile(sessionDir: string): string {\n mkdirSync(sessionDir, { recursive: true });\n const filename = createSessionFilename();\n const filePath = join(sessionDir, filename);\n atomicWritePrivateFile(filePath, \"\");\n atomicWritePrivateFile(join(sessionDir, \"current\"), filename);\n return filePath;\n}\n\n/**\n * Creates a new persistent session file with a proper SessionManager header and cwd.\n * Also updates the \"current\" pointer. Header is written before the pointer flips so a\n * partial create cannot leave \"current\" pointing at a missing file.\n */\nexport function createManagedSessionFile(sessionDir: string, cwd: string): string {\n mkdirSync(sessionDir, { recursive: true });\n const sessionId = randomUUID();\n const sessionFile = join(sessionDir, createSessionFilename(sessionId));\n writeSessionHeader(sessionFile, cwd, sessionId);\n setCurrentPointer(sessionDir, sessionFile);\n return sessionFile;\n}\n\n/**\n * Open a session file with an explicit cwd, even if the file does not exist yet.\n * This avoids SessionStore.open() falling back to process.cwd() for fresh sessions.\n */\nexport function openManagedSession(sessionFile: string, cwd: string): SessionStore {\n if (shouldRecreatePreinitializedSession(sessionFile)) {\n rmSync(sessionFile, { force: true });\n }\n\n return SessionStore.open(sessionFile, cwd);\n}\n\nfunction createSessionFilename(sessionId = randomUUID()): string {\n const timestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n return `${timestamp}_${sessionId.slice(0, 8)}.jsonl`;\n}\n\nfunction setCurrentPointer(sessionDir: string, sessionFilePath: string): void {\n const filename = sessionFilePath.split(\"/\").pop()!;\n mkdirSync(sessionDir, { recursive: true });\n atomicWritePrivateFile(join(sessionDir, \"current\"), filename);\n}\n\n/**\n * Creates or overwrites a fixed-path session file with a valid session header.\n */\nexport interface ParentSessionRef {\n path: string;\n id: string;\n}\n\nexport function createManagedSessionFileAtPath(\n sessionFile: string,\n cwd: string,\n parent?: ParentSessionRef,\n): string {\n writeSessionHeader(sessionFile, cwd, undefined, parent);\n return sessionFile;\n}\n\nfunction writeSessionHeader(\n sessionFile: string,\n cwd: string,\n sessionId = randomUUID(),\n parent?: ParentSessionRef,\n): void {\n mkdirSync(dirname(sessionFile), { recursive: true });\n // The header format (and its version) is owned by the harness store; this\n // layer only decides the path and the id.\n SessionStore.create(sessionFile, cwd, {\n id: sessionId,\n ...(parent ? { parentSession: parent.path, parentSessionId: parent.id } : {}),\n });\n}\n\n/**\n * Returns the fixed session file path for a Slack thread.\n */\nexport function getThreadSessionFile(channelDir: string, sessionKey: string): string {\n const sessionDir = getChannelSessionDir(channelDir);\n return resolveChildPath(sessionDir, `${extractSessionSuffix(sessionKey)}.jsonl`);\n}\n\nfunction isRegularSessionFile(sessionFile: string): boolean {\n try {\n return lstatSync(sessionFile).isFile();\n } catch {\n return false;\n }\n}\n\nfunction hasSessionHeader(sessionFile: string): boolean {\n try {\n const raw = readTextFileIfExists(sessionFile);\n if (raw === undefined) return false;\n const lines = raw.split(\"\\n\");\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n const entry = parseSessionEntry(trimmed);\n return entry.type === \"session\";\n }\n } catch {\n return false;\n }\n return false;\n}\n\nfunction shouldRecreatePreinitializedSession(sessionFile: string): boolean {\n try {\n const raw = readTextFileIfExists(sessionFile);\n if (raw === undefined) return false;\n const entries = raw\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean)\n .map(parseSessionEntry);\n\n if (entries.length !== 1 || entries[0]?.type !== \"session\") return false;\n // Sessions with lineage metadata are fully initialized — preserve them.\n const h = entries[0] as { parentSession?: unknown; parentSessionId?: unknown };\n if (h.parentSession || h.parentSessionId) return false;\n return true;\n } catch {\n return false;\n }\n}\n\nfunction parseSessionEntry(line: string): { type?: string } {\n return parseJsonValue(\n line,\n (value): value is { type?: string } => isRecord(value),\n (detail) => (detail === \"unexpected JSON shape\" ? \"expected a JSON object\" : detail),\n );\n}\n\nfunction getCurrentSessionPath(sessionDir: string): string | null {\n const pointerFile = join(sessionDir, \"current\");\n const filename = readTextFileIfExists(pointerFile)?.trim();\n if (!filename) return null;\n try {\n return resolveChildPath(sessionDir, filename);\n } catch {\n return null;\n }\n}\n\n/**\n * Try to resolve an existing current session file.\n * Returns null if no current pointer exists or the pointed file has no valid session header.\n */\nexport function tryResolveCurrentSession(sessionDir: string): string | null {\n const fullPath = getCurrentSessionPath(sessionDir);\n if (fullPath && isRegularSessionFile(fullPath) && hasSessionHeader(fullPath)) return fullPath;\n return null;\n}\n\n/**\n * Try to resolve an existing thread session file.\n * Returns the file path if found, or null if no valid thread session exists yet.\n */\nexport function tryResolveThreadSession(sessionFile: string): string | null {\n return isRegularSessionFile(sessionFile) && hasSessionHeader(sessionFile) ? sessionFile : null;\n}\n\n/**\n * Resolve the channel's current session file path.\n * Returns null if no channel session exists.\n */\nexport function resolveChannelSessionFile(channelDir: string): string | null {\n return tryResolveCurrentSession(getChannelSessionDir(channelDir));\n}\n\n// Matches timestamped main session filenames; thread sessions use bare threadTs.\nconst MAIN_SESSION_FILENAME = /^\\d{4}-\\d{2}-\\d{2}T.+_[0-9a-f]{8}\\.jsonl$/i;\n\n/**\n * Resolve the main session file that was active when a thread was created.\n * Uses the thread's Slack timestamp to find the main session whose creation\n * time is the latest one at or before that moment — stable across rotations.\n * Falls back to resolveChannelSessionFile when threadTs is absent or unparseable.\n * Returns both path and session UUID so callers can store a UUID-stable reference.\n */\nexport function resolveParentSessionForThread(\n channelDir: string,\n threadTs: string | undefined,\n): ParentSessionRef | null {\n if (threadTs !== undefined) {\n const threadTimeMs = Number(threadTs) * 1000;\n if (Number.isFinite(threadTimeMs)) {\n const best = findMainSessionActiveAtTime(channelDir, threadTimeMs);\n if (best) return best;\n }\n }\n const path = resolveChannelSessionFile(channelDir);\n if (!path) return null;\n const id = readSessionHeaderSummary(path)?.id;\n return id ? { path, id } : null;\n}\n\nfunction findMainSessionActiveAtTime(\n channelDir: string,\n targetMs: number,\n): ParentSessionRef | null {\n const sessionDir = getChannelSessionDir(channelDir);\n if (!existsSync(sessionDir)) return null;\n\n let best: ParentSessionRef | null = null;\n let bestCreatedMs = -Infinity;\n\n for (const name of readdirSync(sessionDir)) {\n if (!MAIN_SESSION_FILENAME.test(name)) continue;\n const filePath = join(sessionDir, name);\n const summary = readSessionHeaderSummary(filePath);\n if (!summary) continue;\n if (summary.timestampMs <= targetMs && summary.timestampMs > bestCreatedMs) {\n bestCreatedMs = summary.timestampMs;\n best = { path: filePath, id: summary.id };\n }\n }\n return best;\n}\n\nfunction readSessionHeaderSummary(filePath: string): { id: string; timestampMs: number } | null {\n try {\n const raw = readTextFileIfExists(filePath);\n if (!raw) return null;\n const firstLine = raw.slice(0, raw.indexOf(\"\\n\")).trim();\n if (!firstLine) return null;\n const entry = parseSessionEntry(firstLine);\n const { id, timestamp } = entry as { id?: unknown; timestamp?: unknown };\n if (typeof id !== \"string\" || typeof timestamp !== \"string\") return null;\n const timestampMs = new Date(timestamp).getTime();\n return Number.isFinite(timestampMs) ? { id, timestampMs } : null;\n } catch {\n return null;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/sessions/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAChF,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC5E,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EACL,sBAAsB,EACtB,QAAQ,EACR,cAAc,EACd,oBAAoB,GACrB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAKvE,MAAM,UAAU,wBAAwB,CAAC,WAAmB;IAC1D,IAAI,CAAC;QAC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AAI,EAAE,CAAC;QACzD,IAAI,CAAC,SAAS;YAAE,OAAO,IAAI,CAAC;QAC5B,MAAM,KAAK,GAAG,iBAAiB,CAAC,SAAS,CAAC,CAAC;QAC3C,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,GAAG,KAA8C,CAAC;QACzE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,OAAO,SAAS,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAC;QACzE,MAAM,WAAW,GAAG,IAAI,IAAI,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,CAAC;QAClD,OAAO,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IACnE,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { existsSync, lstatSync, mkdirSync, readdirSync, rmSync } from \"node:fs\";\nimport { basename, dirname, join, relative, resolve, sep } from \"node:path\";\nimport { SessionStore } from \"../harness/index.js\";\nimport {\n atomicWritePrivateFile,\n isRecord,\n parseJsonValue,\n readTextFileIfExists,\n} from \"../utils/file-guards.js\";\nimport { officeSessionsDir } from \"../office/index.js\";\nimport { assertSessionSuffix, threadSuffixOf } from \"./session-key.js\";\nexport type { ResolvedSessionScope, ThreadRootMessage } from \"./types.js\";\nexport type { MikanSessionHeader } from \"./types.js\";\nimport type { MikanSessionHeader } from \"./types.js\";\n\nexport function isPlatformHistorySession(sessionFile: string): boolean {\n try {\n const header = SessionStore.open(sessionFile).getHeader() as MikanSessionHeader | null;\n return header?.source?.kind === \"platform-history\";\n } catch {\n return false;\n }\n}\n\n/**\n * Resolves the current active session file for a session directory.\n * Reads the \"current\" pointer file; creates a new session if none exists\n * or the pointed-to file is missing.\n */\nexport function resolveSessionFile(sessionDir: string): string {\n const existing = tryResolveCurrentSession(sessionDir);\n if (existing) return existing;\n return createNewSessionFile(sessionDir);\n}\n\n/**\n * Resolve the current active session file for a session directory.\n * Creates a fully initialized persistent session with the provided cwd when none exists.\n */\nexport function resolveManagedSessionFile(sessionDir: string, cwd: string): string {\n const existingPath = getCurrentSessionPath(sessionDir);\n if (existingPath && !isPlatformHistorySession(existingPath)) return existingPath;\n return createManagedSessionFile(sessionDir, cwd);\n}\n\n/**\n * Extracts the short UUID from a session file path.\n * e.g. \"2026-04-05T00-00_7b54cf90.jsonl\" → \"7b54cf90\"\n */\nexport function extractSessionUuid(sessionFile: string): string {\n return basename(sessionFile).replace(\".jsonl\", \"\").split(\"_\").pop()!;\n}\n\n/**\n * Extracts the thread/suffix part of a session key.\n * \"channelId:threadId\" → \"threadId\", \"channelId\" → \"channelId\"\n */\nexport function extractSessionSuffix(sessionKey: string): string {\n return assertSessionSuffix(threadSuffixOf(sessionKey) ?? sessionKey);\n}\n\n/**\n * Resolve one child path and prove it remains inside its owning directory.\n * Identity validation is the first guard; containment is defense in depth for\n * every session path derived from platform-controlled values.\n */\nfunction resolveChildPath(root: string, child: string): string {\n const resolvedRoot = resolve(root);\n const resolvedChild = resolve(resolvedRoot, child);\n const relation = relative(resolvedRoot, resolvedChild);\n if (!relation || relation === \"..\" || relation.startsWith(`..${sep}`)) {\n throw new Error(`Session path escapes its owning directory: ${JSON.stringify(child)}`);\n }\n return resolvedChild;\n}\n\n/**\n * Creates an empty timestamped file and updates the \"current\" pointer.\n * Used only by tests for placeholder-file scenarios.\n *\n * Order matters: write the session file first, then atomic-rename the pointer\n * last so a crash mid-create never leaves \"current\" pointing at a missing file.\n */\nexport function createNewSessionFile(sessionDir: string): string {\n mkdirSync(sessionDir, { recursive: true });\n const filename = createSessionFilename();\n const filePath = join(sessionDir, filename);\n atomicWritePrivateFile(filePath, \"\");\n atomicWritePrivateFile(join(sessionDir, \"current\"), filename);\n return filePath;\n}\n\n/**\n * Creates a new persistent session file with a proper SessionManager header and cwd.\n * Also updates the \"current\" pointer. Header is written before the pointer flips so a\n * partial create cannot leave \"current\" pointing at a missing file.\n */\nexport function createManagedSessionFile(sessionDir: string, cwd: string): string {\n mkdirSync(sessionDir, { recursive: true });\n const sessionId = randomUUID();\n const sessionFile = join(sessionDir, createSessionFilename(sessionId));\n writeSessionHeader(sessionFile, cwd, sessionId);\n setCurrentPointer(sessionDir, sessionFile);\n return sessionFile;\n}\n\n/**\n * Open a session file with an explicit cwd, even if the file does not exist yet.\n * This avoids SessionStore.open() falling back to process.cwd() for fresh sessions.\n */\nexport function openManagedSession(sessionFile: string, cwd: string): SessionStore {\n if (shouldRecreatePreinitializedSession(sessionFile)) {\n rmSync(sessionFile, { force: true });\n }\n\n return SessionStore.open(sessionFile, cwd);\n}\n\nfunction createSessionFilename(sessionId = randomUUID()): string {\n const timestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n return `${timestamp}_${sessionId.slice(0, 8)}.jsonl`;\n}\n\nfunction setCurrentPointer(sessionDir: string, sessionFilePath: string): void {\n const filename = sessionFilePath.split(\"/\").pop()!;\n mkdirSync(sessionDir, { recursive: true });\n atomicWritePrivateFile(join(sessionDir, \"current\"), filename);\n}\n\n/**\n * Creates or overwrites a fixed-path session file with a valid session header.\n */\nexport interface ParentSessionRef {\n path: string;\n id: string;\n}\n\nexport function createManagedSessionFileAtPath(\n sessionFile: string,\n cwd: string,\n parent?: ParentSessionRef,\n): string {\n writeSessionHeader(sessionFile, cwd, undefined, parent);\n return sessionFile;\n}\n\nfunction writeSessionHeader(\n sessionFile: string,\n cwd: string,\n sessionId = randomUUID(),\n parent?: ParentSessionRef,\n): void {\n mkdirSync(dirname(sessionFile), { recursive: true });\n // The header format (and its version) is owned by the harness store; this\n // layer only decides the path and the id.\n SessionStore.create(sessionFile, cwd, {\n id: sessionId,\n ...(parent ? { parentSession: parent.path, parentSessionId: parent.id } : {}),\n });\n}\n\n/**\n * Returns the fixed session file path for a Slack thread.\n */\nexport function getThreadSessionFile(channelDir: string, sessionKey: string): string {\n const sessionDir = officeSessionsDir(channelDir);\n return resolveChildPath(sessionDir, `${extractSessionSuffix(sessionKey)}.jsonl`);\n}\n\nfunction isRegularSessionFile(sessionFile: string): boolean {\n try {\n return lstatSync(sessionFile).isFile();\n } catch {\n return false;\n }\n}\n\nfunction hasSessionHeader(sessionFile: string): boolean {\n try {\n const raw = readTextFileIfExists(sessionFile);\n if (raw === undefined) return false;\n const lines = raw.split(\"\\n\");\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n const entry = parseSessionEntry(trimmed);\n return entry.type === \"session\";\n }\n } catch {\n return false;\n }\n return false;\n}\n\nfunction shouldRecreatePreinitializedSession(sessionFile: string): boolean {\n try {\n const raw = readTextFileIfExists(sessionFile);\n if (raw === undefined) return false;\n const entries = raw\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean)\n .map(parseSessionEntry);\n\n if (entries.length !== 1 || entries[0]?.type !== \"session\") return false;\n // Sessions with lineage metadata are fully initialized — preserve them.\n const h = entries[0] as { parentSession?: unknown; parentSessionId?: unknown };\n if (h.parentSession || h.parentSessionId) return false;\n return true;\n } catch {\n return false;\n }\n}\n\nfunction parseSessionEntry(line: string): { type?: string } {\n return parseJsonValue(\n line,\n (value): value is { type?: string } => isRecord(value),\n (detail) => (detail === \"unexpected JSON shape\" ? \"expected a JSON object\" : detail),\n );\n}\n\nfunction getCurrentSessionPath(sessionDir: string): string | null {\n const pointerFile = join(sessionDir, \"current\");\n const filename = readTextFileIfExists(pointerFile)?.trim();\n if (!filename) return null;\n try {\n return resolveChildPath(sessionDir, filename);\n } catch {\n return null;\n }\n}\n\n/**\n * Try to resolve an existing current session file.\n * Returns null if no current pointer exists or the pointed file has no valid session header.\n */\nexport function tryResolveCurrentSession(sessionDir: string): string | null {\n const fullPath = getCurrentSessionPath(sessionDir);\n if (fullPath && isRegularSessionFile(fullPath) && hasSessionHeader(fullPath)) return fullPath;\n return null;\n}\n\n/**\n * Try to resolve an existing thread session file.\n * Returns the file path if found, or null if no valid thread session exists yet.\n */\nexport function tryResolveThreadSession(sessionFile: string): string | null {\n return isRegularSessionFile(sessionFile) && hasSessionHeader(sessionFile) ? sessionFile : null;\n}\n\n/**\n * Resolve the channel's current session file path.\n * Returns null if no channel session exists.\n */\nexport function resolveChannelSessionFile(channelDir: string): string | null {\n return tryResolveCurrentSession(officeSessionsDir(channelDir));\n}\n\n// Matches timestamped main session filenames; thread sessions use bare threadTs.\nconst MAIN_SESSION_FILENAME = /^\\d{4}-\\d{2}-\\d{2}T.+_[0-9a-f]{8}\\.jsonl$/i;\n\n/**\n * Resolve the main session file that was active when a thread was created.\n * Uses the thread's Slack timestamp to find the main session whose creation\n * time is the latest one at or before that moment — stable across rotations.\n * Falls back to resolveChannelSessionFile when threadTs is absent or unparseable.\n * Returns both path and session UUID so callers can store a UUID-stable reference.\n */\nexport function resolveParentSessionForThread(\n channelDir: string,\n threadTs: string | undefined,\n): ParentSessionRef | null {\n if (threadTs !== undefined) {\n const threadTimeMs = Number(threadTs) * 1000;\n if (Number.isFinite(threadTimeMs)) {\n const best = findMainSessionActiveAtTime(channelDir, threadTimeMs);\n if (best) return best;\n }\n }\n const path = resolveChannelSessionFile(channelDir);\n if (!path) return null;\n const id = readSessionHeaderSummary(path)?.id;\n return id ? { path, id } : null;\n}\n\nfunction findMainSessionActiveAtTime(\n channelDir: string,\n targetMs: number,\n): ParentSessionRef | null {\n const sessionDir = officeSessionsDir(channelDir);\n if (!existsSync(sessionDir)) return null;\n\n let best: ParentSessionRef | null = null;\n let bestCreatedMs = -Infinity;\n\n for (const name of readdirSync(sessionDir)) {\n if (!MAIN_SESSION_FILENAME.test(name)) continue;\n const filePath = join(sessionDir, name);\n const summary = readSessionHeaderSummary(filePath);\n if (!summary) continue;\n if (summary.timestampMs <= targetMs && summary.timestampMs > bestCreatedMs) {\n bestCreatedMs = summary.timestampMs;\n best = { path: filePath, id: summary.id };\n }\n }\n return best;\n}\n\nfunction readSessionHeaderSummary(filePath: string): { id: string; timestampMs: number } | null {\n try {\n const raw = readTextFileIfExists(filePath);\n if (!raw) return null;\n const firstLine = raw.slice(0, raw.indexOf(\"\\n\")).trim();\n if (!firstLine) return null;\n const entry = parseSessionEntry(firstLine);\n const { id, timestamp } = entry as { id?: unknown; timestamp?: unknown };\n if (typeof id !== \"string\" || typeof timestamp !== \"string\") return null;\n const timestampMs = new Date(timestamp).getTime();\n return Number.isFinite(timestampMs) ? { id, timestampMs } : null;\n } catch {\n return null;\n }\n}\n"]}
|
package/dist/sessions/types.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ConversationKind } from "../adapter.js";
|
|
2
|
+
import type { SessionStore } from "../harness/index.js";
|
|
2
3
|
import type { ConversationLogMessage } from "../types.js";
|
|
3
4
|
export interface MikanSessionHeader {
|
|
4
5
|
type?: string;
|
|
@@ -62,7 +63,7 @@ export interface ResolveChatSessionScopeOptions {
|
|
|
62
63
|
export interface SyncChatSessionOptions {
|
|
63
64
|
conversationDir: string;
|
|
64
65
|
sessionKey: string;
|
|
65
|
-
sessionManager:
|
|
66
|
+
sessionManager: SessionStore;
|
|
66
67
|
/** The triggering platform message ID. Sync is capped before this turn to avoid future queued turns. */
|
|
67
68
|
currentMessageId?: string;
|
|
68
69
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/sessions/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAI1D,MAAM,WAAW,kBAAkB;IACjC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,aAAa,CAAC,EAAE,MAA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AAE,MAAM,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,6BAA6B;IAC5C,eAAe,EAAE,MAAM,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,0BAA0B;IACzC,gBAAgB,EAAE,MAAM,CAAC;IACzB,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,EAAE,MAAM,OAAO,CAAC;IAChC,eAAe,EAAE,MAAM,OAAO,CAAC;IAC/B,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACtC,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/sessions/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ConversationKind } from \"../adapter.js\";\nimport type { ConversationLogMessage } from \"../types.js\";\n\n// ── session metadata ─────────────────────────────────────────────────────────\n\nexport interface MikanSessionHeader {\n type?: string;\n version?: number;\n id?: string;\n timestamp?: string;\n cwd?: string;\n parentSession?: string;\n source?: {\n kind?: string;\n file?: string;\n recentDays?: number;\n };\n}\n\n// ── session policy ───────────────────────────────────────────────────────────\n\nexport interface ResolveSessionKeyOptions {\n conversationId: string;\n conversationKind: ConversationKind;\n messageId: string;\n threadTs?: string;\n persistentTopLevel?: boolean;\n scopeDirectThreads?: boolean;\n}\n\n// ── session store ────────────────────────────────────────────────────────────\n\nexport interface ThreadRootMessage {\n text?: string;\n userName?: string;\n user?: string;\n loggedAt?: number;\n isMessagingBot?: boolean;\n}\n\nexport interface ResolvedSessionScope {\n sessionDir: string;\n contextFile: string;\n threadRootMessage: ThreadRootMessage | null;\n}\n\n/** One parsed log.jsonl entry with its original line index. */\nexport interface LogRecord {\n message: ConversationLogMessage;\n index: number;\n}\n\n// ── chat history sync ────────────────────────────────────────────────────────\n\n/** What one sync pass actually did — the inspectable result of a sync. */\nexport interface ChatSyncReport {\n /** Log messages appended to the session in this pass. */\n appended: number;\n /** The log message id recorded as the new sync watermark. */\n lastMessageId?: string;\n}\n\nexport interface ChatHistorySyncOptions {\n recentDays?: number;\n maxTopLevelMessages?: number;\n now?: () => Date;\n}\n\nexport interface ResolveChatSessionScopeOptions {\n conversationDir: string;\n sessionKey: string;\n cwd?: string;\n /** The triggering platform message ID. History is capped before this turn to avoid future queued turns. */\n currentMessageId?: string;\n /** Rotate top-level shared sessions on biweekly Sunday boundaries. */\n rotateTopLevelSession?: boolean;\n}\n\nexport interface SyncChatSessionOptions {\n conversationDir: string;\n sessionKey: string;\n sessionManager:
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/sessions/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ConversationKind } from \"../adapter.js\";\nimport type { SessionStore } from \"../harness/index.js\";\nimport type { ConversationLogMessage } from \"../types.js\";\n\n// ── session metadata ─────────────────────────────────────────────────────────\n\nexport interface MikanSessionHeader {\n type?: string;\n version?: number;\n id?: string;\n timestamp?: string;\n cwd?: string;\n parentSession?: string;\n source?: {\n kind?: string;\n file?: string;\n recentDays?: number;\n };\n}\n\n// ── session policy ───────────────────────────────────────────────────────────\n\nexport interface ResolveSessionKeyOptions {\n conversationId: string;\n conversationKind: ConversationKind;\n messageId: string;\n threadTs?: string;\n persistentTopLevel?: boolean;\n scopeDirectThreads?: boolean;\n}\n\n// ── session store ────────────────────────────────────────────────────────────\n\nexport interface ThreadRootMessage {\n text?: string;\n userName?: string;\n user?: string;\n loggedAt?: number;\n isMessagingBot?: boolean;\n}\n\nexport interface ResolvedSessionScope {\n sessionDir: string;\n contextFile: string;\n threadRootMessage: ThreadRootMessage | null;\n}\n\n/** One parsed log.jsonl entry with its original line index. */\nexport interface LogRecord {\n message: ConversationLogMessage;\n index: number;\n}\n\n// ── chat history sync ────────────────────────────────────────────────────────\n\n/** What one sync pass actually did — the inspectable result of a sync. */\nexport interface ChatSyncReport {\n /** Log messages appended to the session in this pass. */\n appended: number;\n /** The log message id recorded as the new sync watermark. */\n lastMessageId?: string;\n}\n\nexport interface ChatHistorySyncOptions {\n recentDays?: number;\n maxTopLevelMessages?: number;\n now?: () => Date;\n}\n\nexport interface ResolveChatSessionScopeOptions {\n conversationDir: string;\n sessionKey: string;\n cwd?: string;\n /** The triggering platform message ID. History is capped before this turn to avoid future queued turns. */\n currentMessageId?: string;\n /** Rotate top-level shared sessions on biweekly Sunday boundaries. */\n rotateTopLevelSession?: boolean;\n}\n\nexport interface SyncChatSessionOptions {\n conversationDir: string;\n sessionKey: string;\n sessionManager: SessionStore;\n /** The triggering platform message ID. Sync is capped before this turn to avoid future queued turns. */\n currentMessageId?: string;\n}\n\nexport interface ResetChatSessionOptions {\n conversationDir: string;\n sessionKey: string;\n cwd?: string;\n}\n\nexport interface RegisterThreadSessionOptions {\n conversationDir: string;\n sessionKey: string;\n cwd?: string;\n}\n\nexport interface HasMaterializedSessionOptions {\n conversationDir: string;\n sessionKey: string;\n}\n\nexport interface ThreadBootstrapWaitOptions {\n parentSessionKey: string;\n sessionKey: string;\n hasThreadSession: () => boolean;\n isParentRunning: () => boolean;\n sleep?: (ms: number) => Promise<void>;\n pollMs?: number;\n}\n"]}
|
package/dist/tools/bash.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
2
|
import { Type } from "@sinclair/typebox";
|
|
3
|
-
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail, } from "
|
|
3
|
+
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail, } from "@earendil-works/pi-agent-core";
|
|
4
4
|
/**
|
|
5
5
|
* Spill path for oversized bash output, inside the runtime workspace so the
|
|
6
6
|
* model can actually read the file it is pointed at (a host tmpdir path is a
|
package/dist/tools/bash.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash.js","sourceRoot":"","sources":["../../src/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAEzC,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,UAAU,EAEV,YAAY,GACb,MAAM,
|
|
1
|
+
{"version":3,"file":"bash.js","sourceRoot":"","sources":["../../src/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAEzC,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,UAAU,EAEV,YAAY,GACb,MAAM,+BAA+B,CAAC;AAEvC;;;;GAIG;AACH,SAAS,YAAY,CAAC,oBAA4B;IAChD,MAAM,EAAE,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC1C,OAAO,GAAG,oBAAoB,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,uBAAuB,EAAE,MAAM,CAAC;AACpF,CAAC;AAED,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;IAC7B,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC;QACjB,WAAW,EAAE,6DAA6D;KAC3E,CAAC;IACF,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,yBAAyB,EAAE,CAAC;IAChE,OAAO,EAAE,IAAI,CAAC,QAAQ,CACpB,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,mDAAmD,EAAE,CAAC,CAClF;CACF,CAAC,CAAC;AAOH,MAAM,UAAU,cAAc,CAC5B,QAAkB,EAClB,OAAwC;IAExC,OAAO;QACL,IAAI,EAAE,MAAM;QACZ,KAAK,EAAE,MAAM;QACb,aAAa,EAAE,YAA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,CAAC,GAAG,UAAU,gCAAgC,MAAM,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;YACrF,CAAC;YAED,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC;QACpE,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Type } from \"@sinclair/typebox\";\nimport type { Executor } from \"../sandbox/index.js\";\nimport {\n DEFAULT_MAX_BYTES,\n DEFAULT_MAX_LINES,\n formatSize,\n type TruncationResult,\n truncateTail,\n} from \"@earendil-works/pi-agent-core\";\n\n/**\n * Spill path for oversized bash output, inside the runtime workspace so the\n * model can actually read the file it is pointed at (a host tmpdir path is a\n * dead pointer inside sandbox containers — see src/sandbox/README.md).\n */\nfunction getSpillPath(runtimeWorkspaceRoot: string): string {\n const id = randomBytes(8).toString(\"hex\");\n return `${runtimeWorkspaceRoot.replace(/\\/+$/, \"\")}/.mikan/bash-output/${id}.log`;\n}\n\nconst bashSchema = Type.Object({\n label: Type.String({\n description: \"Brief description of what this command does (shown to user)\",\n }),\n command: Type.String({ description: \"Bash command to execute\" }),\n timeout: Type.Optional(\n Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" }),\n ),\n});\n\ninterface BashToolDetails {\n truncation?: TruncationResult;\n fullOutputPath?: string;\n}\n\nexport function createBashTool(\n executor: Executor,\n options?: { hostWorkspaceRoot?: string },\n): AgentTool<typeof bashSchema> {\n return {\n name: \"bash\",\n label: \"bash\",\n executionMode: \"sequential\",\n description: `Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n parameters: bashSchema,\n execute: async (\n _toolCallId: string,\n { command, timeout }: { label: string; command: string; timeout?: number },\n signal?: AbortSignal,\n ) => {\n let tempFilePath: string | undefined;\n\n const result = await executor.exec(command, { timeout, signal });\n let output = \"\";\n if (result.stdout) output += result.stdout;\n if (result.stderr) {\n if (output) output += \"\\n\";\n output += result.stderr;\n }\n\n const totalBytes = Buffer.byteLength(output, \"utf-8\");\n\n // Spill the full output into the runtime workspace when it exceeds the\n // limit; the executor owns transport, so the advertised path is valid\n // where the model's follow-up read/bash actually runs.\n if (totalBytes > DEFAULT_MAX_BYTES) {\n const runtimeRoot = executor.getPathContext(\n options?.hostWorkspaceRoot ?? process.cwd(),\n ).runtimeWorkspaceRoot;\n const spillPath = getSpillPath(runtimeRoot);\n try {\n await executor.writeFile(spillPath, output, { signal });\n tempFilePath = spillPath;\n } catch {\n tempFilePath = undefined;\n }\n }\n\n // Apply tail truncation\n const truncation = truncateTail(output);\n let outputText = truncation.content || \"(no output)\";\n\n // Build details with truncation info\n let details: BashToolDetails | undefined;\n\n if (truncation.truncated) {\n details = {\n truncation,\n fullOutputPath: tempFilePath,\n };\n\n // Build actionable notice\n const startLine = truncation.totalLines - truncation.outputLines + 1;\n const endLine = truncation.totalLines;\n const fullOutputNote = tempFilePath\n ? ` Full output: ${tempFilePath}`\n : \" Full output unavailable (spill failed).\";\n\n if (truncation.lastLinePartial) {\n // Edge case: last line alone > 50KB\n const lastLineSize = formatSize(\n Buffer.byteLength(output.split(\"\\n\").pop() || \"\", \"utf-8\"),\n );\n outputText += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}).${fullOutputNote}]`;\n } else if (truncation.truncatedBy === \"lines\") {\n outputText += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}.${fullOutputNote}]`;\n } else {\n outputText += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit).${fullOutputNote}]`;\n }\n }\n\n if (result.code !== 0) {\n throw new Error(`${outputText}\\n\\nCommand exited with code ${result.code}`.trim());\n }\n\n return { content: [{ type: \"text\", text: outputText }], details };\n },\n };\n}\n"]}
|
package/dist/tools/edit.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../src/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAG/D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../src/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAG/D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAuFpD,QAAA,MAAM,UAAU;;;;;EAOd,CAAC;AAEH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,QAAQ,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAkE/E"}
|
package/dist/tools/edit.js
CHANGED
|
@@ -15,6 +15,8 @@ function generateDiffString(oldContent, newContent, contextLines = 4) {
|
|
|
15
15
|
let lastWasChange = false;
|
|
16
16
|
for (let i = 0; i < parts.length; i++) {
|
|
17
17
|
const part = parts[i];
|
|
18
|
+
if (part === undefined)
|
|
19
|
+
continue;
|
|
18
20
|
const raw = part.value.split("\n");
|
|
19
21
|
if (raw[raw.length - 1] === "") {
|
|
20
22
|
raw.pop();
|
|
@@ -35,7 +37,8 @@ function generateDiffString(oldContent, newContent, contextLines = 4) {
|
|
|
35
37
|
lastWasChange = true;
|
|
36
38
|
}
|
|
37
39
|
else {
|
|
38
|
-
const
|
|
40
|
+
const nextPart = parts[i + 1];
|
|
41
|
+
const nextPartIsChange = nextPart !== undefined && (nextPart.added || nextPart.removed);
|
|
39
42
|
if (lastWasChange || nextPartIsChange) {
|
|
40
43
|
let lines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AI,WAAW,GAAG,CAAC,EAAE,CAAC;gBACpB,MAAM,IAAI,KAAK,CACb,SAAS,WAAW,+BAA+B,IAAI,2EAA2E,CACnI,CAAC;YACJ,CAAC;YAED,sBAAsB;YACtB,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;YACvC,MAAM,UAAU,GACd,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,KAAK,CAAC,GAAG,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;YAEpF,IAAI,OAAO,KAAK,UAAU,EAAE,CAAC;gBAC3B,MAAM,IAAI,KAAK,CACb,sBAAsB,IAAI,0IAA0I,CACrK,CAAC;YACJ,CAAC;YAED,sBAAsB;YACtB,MAAM,QAAQ,CAAC,SAAS,CAAC,IAAI,EAAE,UAAU,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;YAEvD,OAAO;gBACL,OAAO,EAAE;oBACP;wBACE,IAAI,EAAE,MAAM;wBACZ,IAAI,EAAE,iCAAiC,IAAI,aAAa,OAAO,CAAC,MAAM,kBAAkB,OAAO,CAAC,MAAM,cAAc;qBACrH;iBACF;gBACD,OAAO,EAAE,EAAE,IAAI,EAAE,kBAAkB,CAAC,OAAO,EAAE,UAAU,CAAC,EAAE;aAC3D,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Type } from \"@sinclair/typebox\";\nimport * as Diff from \"diff\";\nimport type { Executor } from \"../sandbox/index.js\";\n\n/**\n * Generate a unified diff string with line numbers and context\n */\nfunction generateDiffString(oldContent: string, newContent: string, contextLines = 4): string {\n const parts = Diff.diffLines(oldContent, newContent);\n const output: string[] = [];\n\n const oldLines = oldContent.split(\"\\n\");\n const newLines = newContent.split(\"\\n\");\n const maxLineNum = Math.max(oldLines.length, newLines.length);\n const lineNumWidth = String(maxLineNum).length;\n\n let oldLineNum = 1;\n let newLineNum = 1;\n let lastWasChange = false;\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n const raw = part.value.split(\"\\n\");\n if (raw[raw.length - 1] === \"\") {\n raw.pop();\n }\n\n if (part.added || part.removed) {\n for (const line of raw) {\n if (part.added) {\n const lineNum = String(newLineNum).padStart(lineNumWidth, \" \");\n output.push(`+${lineNum} ${line}`);\n newLineNum++;\n } else {\n const lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n output.push(`-${lineNum} ${line}`);\n oldLineNum++;\n }\n }\n lastWasChange = true;\n } else {\n const nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);\n\n if (lastWasChange || nextPartIsChange) {\n let linesToShow = raw;\n let skipStart = 0;\n let skipEnd = 0;\n\n if (!lastWasChange) {\n skipStart = Math.max(0, raw.length - contextLines);\n linesToShow = raw.slice(skipStart);\n }\n\n if (!nextPartIsChange && linesToShow.length > contextLines) {\n skipEnd = linesToShow.length - contextLines;\n linesToShow = linesToShow.slice(0, contextLines);\n }\n\n if (skipStart > 0) {\n output.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n }\n\n for (const line of linesToShow) {\n const lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n output.push(` ${lineNum} ${line}`);\n oldLineNum++;\n newLineNum++;\n }\n\n if (skipEnd > 0) {\n output.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n }\n\n oldLineNum += skipStart + skipEnd;\n newLineNum += skipStart + skipEnd;\n } else {\n oldLineNum += raw.length;\n newLineNum += raw.length;\n }\n\n lastWasChange = false;\n }\n }\n\n return output.join(\"\\n\");\n}\n\nconst editSchema = Type.Object({\n label: Type.String({\n description: \"Brief description of the edit you're making (shown to user)\",\n }),\n path: Type.String({ description: \"Path to the file to edit (relative or absolute)\" }),\n oldText: Type.String({ description: \"Exact text to find and replace (must match exactly)\" }),\n newText: Type.String({ description: \"New text to replace the old text with\" }),\n});\n\nexport function createEditTool(executor: Executor): AgentTool<typeof editSchema> {\n return {\n name: \"edit\",\n label: \"edit\",\n executionMode: \"sequential\",\n description:\n \"Edit a file by replacing exact text. The oldText must match exactly (including whitespace). Use this for precise, surgical edits.\",\n parameters: editSchema,\n execute: async (\n _toolCallId: string,\n { path, oldText, newText }: { label: string; path: string; oldText: string; newText: string },\n signal?: AbortSignal,\n ) => {\n let content: string;\n try {\n content = await executor.readFile(path, { signal });\n } catch (err) {\n throw new Error(\n err instanceof Error && err.message ? err.message : `File not found: ${path}`,\n {\n cause: err,\n },\n );\n }\n\n // Check if old text exists\n if (!content.includes(oldText)) {\n throw new Error(\n `Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`,\n );\n }\n\n // Count occurrences\n const occurrences = content.split(oldText).length - 1;\n\n if (occurrences > 1) {\n throw new Error(\n `Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`,\n );\n }\n\n // Perform replacement\n const index = content.indexOf(oldText);\n const newContent =\n content.substring(0, index) + newText + content.substring(index + oldText.length);\n\n if (content === newContent) {\n throw new Error(\n `No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`,\n );\n }\n\n // Write the file back\n await executor.writeFile(path, newContent, { signal });\n\n return {\n content: [\n {\n type: \"text\",\n text: `Successfully replaced text in ${path}. Changed ${oldText.length} characters to ${newText.length} characters.`,\n },\n ],\n details: { diff: generateDiffString(content, newContent) },\n };\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"edit.js","sourceRoot":"","sources":["../../src/tools/edit.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACzC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAG7B;;GAEG;AACH,SAAS,kBAAkB,CAAC,UAAkB,EAAE,UAAkB,EAAE,YAAY,GAAG,CAAC;IAClF,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,UAAU,EAAE,UAAU,C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OAAO,KAAK,UAAU,EAAE,CAAC;gBAC3B,MAAM,IAAI,KAAK,CACb,sBAAsB,IAAI,0IAA0I,CACrK,CAAC;YACJ,CAAC;YAED,sBAAsB;YACtB,MAAM,QAAQ,CAAC,SAAS,CAAC,IAAI,EAAE,UAAU,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;YAEvD,OAAO;gBACL,OAAO,EAAE;oBACP;wBACE,IAAI,EAAE,MAAM;wBACZ,IAAI,EAAE,iCAAiC,IAAI,aAAa,OAAO,CAAC,MAAM,kBAAkB,OAAO,CAAC,MAAM,cAAc;qBACrH;iBACF;gBACD,OAAO,EAAE,EAAE,IAAI,EAAE,kBAAkB,CAAC,OAAO,EAAE,UAAU,CAAC,EAAE;aAC3D,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Type } from \"@sinclair/typebox\";\nimport * as Diff from \"diff\";\nimport type { Executor } from \"../sandbox/index.js\";\n\n/**\n * Generate a unified diff string with line numbers and context\n */\nfunction generateDiffString(oldContent: string, newContent: string, contextLines = 4): string {\n const parts = Diff.diffLines(oldContent, newContent);\n const output: string[] = [];\n\n const oldLines = oldContent.split(\"\\n\");\n const newLines = newContent.split(\"\\n\");\n const maxLineNum = Math.max(oldLines.length, newLines.length);\n const lineNumWidth = String(maxLineNum).length;\n\n let oldLineNum = 1;\n let newLineNum = 1;\n let lastWasChange = false;\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (part === undefined) continue;\n const raw = part.value.split(\"\\n\");\n if (raw[raw.length - 1] === \"\") {\n raw.pop();\n }\n\n if (part.added || part.removed) {\n for (const line of raw) {\n if (part.added) {\n const lineNum = String(newLineNum).padStart(lineNumWidth, \" \");\n output.push(`+${lineNum} ${line}`);\n newLineNum++;\n } else {\n const lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n output.push(`-${lineNum} ${line}`);\n oldLineNum++;\n }\n }\n lastWasChange = true;\n } else {\n const nextPart = parts[i + 1];\n const nextPartIsChange = nextPart !== undefined && (nextPart.added || nextPart.removed);\n\n if (lastWasChange || nextPartIsChange) {\n let linesToShow = raw;\n let skipStart = 0;\n let skipEnd = 0;\n\n if (!lastWasChange) {\n skipStart = Math.max(0, raw.length - contextLines);\n linesToShow = raw.slice(skipStart);\n }\n\n if (!nextPartIsChange && linesToShow.length > contextLines) {\n skipEnd = linesToShow.length - contextLines;\n linesToShow = linesToShow.slice(0, contextLines);\n }\n\n if (skipStart > 0) {\n output.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n }\n\n for (const line of linesToShow) {\n const lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n output.push(` ${lineNum} ${line}`);\n oldLineNum++;\n newLineNum++;\n }\n\n if (skipEnd > 0) {\n output.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n }\n\n oldLineNum += skipStart + skipEnd;\n newLineNum += skipStart + skipEnd;\n } else {\n oldLineNum += raw.length;\n newLineNum += raw.length;\n }\n\n lastWasChange = false;\n }\n }\n\n return output.join(\"\\n\");\n}\n\nconst editSchema = Type.Object({\n label: Type.String({\n description: \"Brief description of the edit you're making (shown to user)\",\n }),\n path: Type.String({ description: \"Path to the file to edit (relative or absolute)\" }),\n oldText: Type.String({ description: \"Exact text to find and replace (must match exactly)\" }),\n newText: Type.String({ description: \"New text to replace the old text with\" }),\n});\n\nexport function createEditTool(executor: Executor): AgentTool<typeof editSchema> {\n return {\n name: \"edit\",\n label: \"edit\",\n executionMode: \"sequential\",\n description:\n \"Edit a file by replacing exact text. The oldText must match exactly (including whitespace). Use this for precise, surgical edits.\",\n parameters: editSchema,\n execute: async (\n _toolCallId: string,\n { path, oldText, newText }: { label: string; path: string; oldText: string; newText: string },\n signal?: AbortSignal,\n ) => {\n let content: string;\n try {\n content = await executor.readFile(path, { signal });\n } catch (err) {\n throw new Error(\n err instanceof Error && err.message ? err.message : `File not found: ${path}`,\n {\n cause: err,\n },\n );\n }\n\n // Check if old text exists\n if (!content.includes(oldText)) {\n throw new Error(\n `Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`,\n );\n }\n\n // Count occurrences\n const occurrences = content.split(oldText).length - 1;\n\n if (occurrences > 1) {\n throw new Error(\n `Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`,\n );\n }\n\n // Perform replacement\n const index = content.indexOf(oldText);\n const newContent =\n content.substring(0, index) + newText + content.substring(index + oldText.length);\n\n if (content === newContent) {\n throw new Error(\n `No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`,\n );\n }\n\n // Write the file back\n await executor.writeFile(path, newContent, { signal });\n\n return {\n content: [\n {\n type: \"text\",\n text: `Successfully replaced text in ${path}. Changed ${oldText.length} characters to ${newText.length} characters.`,\n },\n ],\n details: { diff: generateDiffString(content, newContent) },\n };\n },\n };\n}\n"]}
|
package/dist/tools/event.js
CHANGED
|
@@ -3,7 +3,7 @@ import { basename, join } from "node:path";
|
|
|
3
3
|
import { Type } from "@sinclair/typebox";
|
|
4
4
|
import { buildEventPayload, EventTypeSchema, parseEventPayload } from "../harness/event-format.js";
|
|
5
5
|
import * as log from "../log.js";
|
|
6
|
-
import { atomicWritePrivateFile } from "../utils/
|
|
6
|
+
import { atomicWritePrivateFile } from "../utils/file-guards.js";
|
|
7
7
|
const eventSchema = Type.Object({
|
|
8
8
|
action: Type.Optional(Type.Union([
|
|
9
9
|
Type.Literal("create"),
|
package/dist/tools/event.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event.js","sourceRoot":"","sources":["../../src/tools/event.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAE3C,OAAO,EAAE,IAAI,EAA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,UAAU,EAAE,EAAE,CAAC,CAAC;IAC3B,OAAO,SAAS,IAAI,OAAO,CAAC;AAC9B,CAAC","sourcesContent":["import { mkdir, readdir, readFile, rm, stat } from \"node:fs/promises\";\nimport { basename, join } from \"node:path\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Type } from \"@sinclair/typebox\";\nimport type { ConversationKind } from \"../adapter.js\";\nimport { buildEventPayload, EventTypeSchema, parseEventPayload } from \"../harness/event-format.js\";\nimport * as log from \"../log.js\";\nimport { atomicWritePrivateFile } from \"../utils/fs-atomic.js\";\n\nconst eventSchema = Type.Object({\n action: Type.Optional(\n Type.Union(\n [\n Type.Literal(\"create\"),\n Type.Literal(\"list\"),\n Type.Literal(\"read\"),\n Type.Literal(\"update\"),\n Type.Literal(\"delete\"),\n ],\n { description: \"CRUD action. Defaults to create for backward compatibility.\" },\n ),\n ),\n filename: Type.Optional(\n Type.String({\n description: \"Event filename for read, update, or delete actions\",\n }),\n ),\n scope: Type.Optional(\n Type.Union([Type.Literal(\"conversation\"), Type.Literal(\"all\")], {\n description:\n \"List scope. Defaults to conversation, which only shows events for the current conversation. Use all only when the user explicitly asks for all events.\",\n }),\n ),\n label: Type.Optional(\n Type.String({\n description: \"Brief description of the event you're scheduling (shown to user)\",\n }),\n ),\n type: Type.Optional(EventTypeSchema),\n text: Type.Optional(\n Type.String({\n description:\n \"A self-contained task for the future run. Include the necessary context, tone, and constraints in the text itself because events do not inherit normal conversation history.\",\n }),\n ),\n at: Type.Optional(\n Type.String({\n description: \"ISO 8601 timestamp with offset, required for one-shot events\",\n }),\n ),\n schedule: Type.Optional(\n Type.String({\n description: \"Cron schedule, required for periodic events\",\n }),\n ),\n timezone: Type.Optional(\n Type.String({\n description: \"IANA timezone, required for periodic events\",\n }),\n ),\n filenamePrefix: Type.Optional(\n Type.String({\n description: \"Optional filename prefix for the event file\",\n }),\n ),\n});\n\ninterface EventToolContext {\n platform: string;\n conversationId: string;\n conversationKind: ConversationKind;\n userId: string;\n}\n\ntype EventToolParams = {\n action?: \"create\" | \"list\" | \"read\" | \"update\" | \"delete\";\n filename?: string;\n scope?: \"conversation\" | \"all\";\n label?: string;\n type?: \"immediate\" | \"one-shot\" | \"periodic\";\n text?: string;\n at?: string;\n schedule?: string;\n timezone?: string;\n filenamePrefix?: string;\n};\n\nexport type { EventPayload, EventStore } from \"./types.js\";\nimport type { EventPayload, EventStore } from \"./types.js\";\n\nexport class HostEventStore implements EventStore {\n constructor(private readonly eventsDir: string) {}\n\n static fromWorkspaceDir(workspaceDir: string): HostEventStore {\n return new HostEventStore(join(workspaceDir, \"events\"));\n }\n\n async write(filename: string, payload: EventPayload): Promise<{ path: string; size: number }> {\n return this.writePayload(filename, payload);\n }\n\n async list(): Promise<\n Array<{ filename: string; payload: EventPayload | null; size: number; mtimeMs: number }>\n > {\n await mkdir(this.eventsDir, { recursive: true });\n const entries = await readdir(this.eventsDir, { withFileTypes: true });\n const events = await Promise.all(\n entries\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".json\"))\n .map(async (entry) => {\n try {\n return await this.read(entry.name);\n } catch {\n // Keep unparseable files visible (payload: null) so consumers can\n // surface and delete them; skip files that vanished mid-listing.\n try {\n const fileStat = await stat(join(this.eventsDir, entry.name));\n return {\n filename: entry.name,\n payload: null,\n size: fileStat.size,\n mtimeMs: fileStat.mtimeMs,\n };\n } catch {\n return null;\n }\n }\n }),\n );\n return events\n .filter((event) => event !== null)\n .toSorted((a, b) => a.filename.localeCompare(b.filename));\n }\n\n async read(\n filename: string,\n ): Promise<{ filename: string; payload: EventPayload; size: number; mtimeMs: number }> {\n const safeFilename = validateEventFilename(filename);\n const filePath = join(this.eventsDir, safeFilename);\n const [raw, fileStat] = await Promise.all([readFile(filePath, \"utf-8\"), stat(filePath)]);\n // Validation (shape, per-type fields, channelId alias) is owned by the\n // event-format module; files that fail it surface as payload:null in\n // list() and as errors here.\n const payload = parseEventPayload(raw, safeFilename);\n return {\n filename: safeFilename,\n payload,\n size: fileStat.size,\n mtimeMs: fileStat.mtimeMs,\n };\n }\n\n async update(filename: string, payload: EventPayload): Promise<{ path: string; size: number }> {\n return this.writePayload(filename, payload, true);\n }\n\n async delete(filename: string): Promise<{ deleted: boolean }> {\n const safeFilename = validateEventFilename(filename);\n await rm(join(this.eventsDir, safeFilename), { force: true });\n return { deleted: true };\n }\n\n private async writePayload(\n filename: string,\n payload: EventPayload,\n requireExisting = false,\n ): Promise<{ path: string; size: number }> {\n await mkdir(this.eventsDir, { recursive: true });\n const safeFilename = validateEventFilename(filename);\n const filePath = join(this.eventsDir, safeFilename);\n if (requireExisting) {\n await stat(filePath);\n }\n atomicWritePrivateFile(filePath, JSON.stringify(payload) + \"\\n\");\n const fileStat = await stat(filePath);\n return { path: filePath, size: fileStat.size };\n }\n}\n\nexport function createEventTool(eventStore: EventStore): {\n tool: AgentTool<typeof eventSchema>;\n setEventContext: (context: EventToolContext) => void;\n} {\n let eventContext: EventToolContext | null = null;\n\n const tool: AgentTool<typeof eventSchema> = {\n name: \"event\",\n label: \"event\",\n description:\n \"CRUD tool for scheduled events. Create immediate, one-shot, or periodic events for the current conversation. List defaults to events for the current conversation only; use scope=all only when the user explicitly asks to list all events. Event text must be self-contained because events do not inherit normal conversation history.\",\n parameters: eventSchema,\n execute: async (_toolCallId: string, params: EventToolParams, signal?: AbortSignal) => {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n if (!eventContext) {\n throw new Error(\"Event context not configured\");\n }\n\n const action = params.action ?? \"create\";\n\n if (action === \"list\") {\n const events = await eventStore.list();\n const { conversationId, platform } = eventContext;\n const scopedEvents =\n params.scope === \"all\"\n ? events\n : events.filter(\n (event) =>\n event.payload?.conversationId === conversationId &&\n // Same raw id on another platform is another office. Files\n // written before payloads carried a platform stay visible.\n (event.payload.platform === undefined || event.payload.platform === platform),\n );\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(\n {\n scope: params.scope ?? \"conversation\",\n conversationId: params.scope === \"all\" ? undefined : conversationId,\n events: scopedEvents,\n },\n null,\n 2,\n ),\n },\n ],\n details: undefined,\n };\n }\n\n if (action === \"read\") {\n const filename = requireFilename(params);\n const event = await eventStore.read(filename);\n return {\n content: [{ type: \"text\", text: JSON.stringify(event, null, 2) }],\n details: undefined,\n };\n }\n\n if (action === \"delete\") {\n const filename = requireFilename(params);\n await eventStore.delete(filename);\n return {\n content: [{ type: \"text\", text: `Deleted event ${filename}` }],\n details: undefined,\n };\n }\n\n const payload = buildToolEventPayload(params, eventContext);\n const filename =\n action === \"update\"\n ? requireFilename(params)\n : `${sanitizeFileSegment(params.filenamePrefix || payload.type || \"event\")}-${Date.now()}.json`;\n\n log.logInfo(\n `${action === \"update\" ? \"Updating\" : \"Writing\"} event file via control plane store: ${filename} (type=${payload.type}, platform=${payload.platform}, conversation=${payload.conversationId})`,\n );\n\n try {\n const result =\n action === \"update\"\n ? await eventStore.update(filename, payload)\n : await eventStore.write(filename, payload);\n log.logInfo(\n `${action === \"update\" ? \"Updated\" : \"Wrote\"} event file via control plane store: ${result.path} (${result.size} bytes)`,\n );\n } catch (err) {\n log.logWarning(\n `Failed to ${action === \"update\" ? \"update\" : \"write\"} event file via control plane store: ${filename}`,\n String(err),\n );\n throw err;\n }\n\n return {\n content: [{ type: \"text\", text: formatEventWriteResult(action, filename, payload) }],\n details: undefined,\n };\n },\n };\n\n return {\n tool,\n setEventContext: (context: EventToolContext) => {\n eventContext = context;\n },\n };\n}\n\nfunction buildToolEventPayload(params: EventToolParams, context: EventToolContext): EventPayload {\n if (!params.type) {\n throw new Error(\"`type` is required for create and update actions\");\n }\n if (!params.text) {\n throw new Error(\"`text` is required for create and update actions\");\n }\n\n // Per-type field rules live in the event-format module. No sessionKey or\n // threadTs in the payload: reminders should fire as top-level messages,\n // not buried in old threads.\n const payload = buildEventPayload({\n type: params.type,\n platform: context.platform,\n conversationId: context.conversationId,\n conversationKind: context.conversationKind,\n userId: context.userId,\n text: params.text,\n at: params.at,\n schedule: params.schedule,\n timezone: params.timezone,\n });\n\n // Tool-side write policy, not format knowledge: a reminder in the past\n // would be deleted unfired by the watcher, so reject it here.\n if (payload.type === \"one-shot\" && new Date(payload.at).getTime() <= Date.now()) {\n throw new Error(\n `\\`at\\` must be in the future; got ${payload.at} (now=${new Date().toISOString()}). Check the timezone offset.`,\n );\n }\n\n return payload;\n}\n\nfunction formatEventWriteResult(\n action: \"create\" | \"update\",\n filename: string,\n payload: EventPayload,\n): string {\n const scheduledVerb = action === \"update\" ? \"Updated\" : \"Scheduled\";\n const immediateVerb = action === \"update\" ? \"Updated\" : \"Queued\";\n const target = payload.platform\n ? `${payload.platform}/${payload.conversationId}`\n : payload.conversationId;\n switch (payload.type) {\n case \"periodic\":\n return `${scheduledVerb} periodic event ${filename} for ${target} (${payload.schedule} ${payload.timezone})`;\n case \"one-shot\":\n return `${scheduledVerb} one-shot event ${filename} for ${target} at ${payload.at}`;\n case \"immediate\":\n return `${immediateVerb} immediate event ${filename} for ${target}`;\n }\n}\n\nfunction requireFilename(params: EventToolParams): string {\n if (!params.filename) {\n throw new Error(\"`filename` is required for read, update, and delete actions\");\n }\n return validateEventFilename(params.filename);\n}\n\nfunction validateEventFilename(filename: string): string {\n const trimmed = filename.trim();\n if (\n !trimmed ||\n trimmed !== basename(trimmed) ||\n trimmed.includes(\"..\") ||\n !trimmed.endsWith(\".json\")\n ) {\n throw new Error(\"Invalid event filename\");\n }\n return trimmed;\n}\n\nfunction sanitizeFileSegment(value: string): string {\n const sanitized = value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return sanitized || \"event\";\n}\n"]}
|
|
1
|
+
{"version":3,"file":"event.js","sourceRoot":"","sources":["../../src/tools/event.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EAAE,QAAQ,EA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;SACb,OAAO,CAAC,gBAAgB,EAAE,GAAG,CAAC;SAC9B,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;IAC3B,OAAO,SAAS,IAAI,OAAO,CAAC;AAC9B,CAAC","sourcesContent":["import { mkdir, readdir, readFile, rm, stat } from \"node:fs/promises\";\nimport { basename, join } from \"node:path\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Type } from \"@sinclair/typebox\";\nimport type { ConversationKind } from \"../adapter.js\";\nimport { buildEventPayload, EventTypeSchema, parseEventPayload } from \"../harness/event-format.js\";\nimport * as log from \"../log.js\";\nimport { atomicWritePrivateFile } from \"../utils/file-guards.js\";\n\nconst eventSchema = Type.Object({\n action: Type.Optional(\n Type.Union(\n [\n Type.Literal(\"create\"),\n Type.Literal(\"list\"),\n Type.Literal(\"read\"),\n Type.Literal(\"update\"),\n Type.Literal(\"delete\"),\n ],\n { description: \"CRUD action. Defaults to create for backward compatibility.\" },\n ),\n ),\n filename: Type.Optional(\n Type.String({\n description: \"Event filename for read, update, or delete actions\",\n }),\n ),\n scope: Type.Optional(\n Type.Union([Type.Literal(\"conversation\"), Type.Literal(\"all\")], {\n description:\n \"List scope. Defaults to conversation, which only shows events for the current conversation. Use all only when the user explicitly asks for all events.\",\n }),\n ),\n label: Type.Optional(\n Type.String({\n description: \"Brief description of the event you're scheduling (shown to user)\",\n }),\n ),\n type: Type.Optional(EventTypeSchema),\n text: Type.Optional(\n Type.String({\n description:\n \"A self-contained task for the future run. Include the necessary context, tone, and constraints in the text itself because events do not inherit normal conversation history.\",\n }),\n ),\n at: Type.Optional(\n Type.String({\n description: \"ISO 8601 timestamp with offset, required for one-shot events\",\n }),\n ),\n schedule: Type.Optional(\n Type.String({\n description: \"Cron schedule, required for periodic events\",\n }),\n ),\n timezone: Type.Optional(\n Type.String({\n description: \"IANA timezone, required for periodic events\",\n }),\n ),\n filenamePrefix: Type.Optional(\n Type.String({\n description: \"Optional filename prefix for the event file\",\n }),\n ),\n});\n\ninterface EventToolContext {\n platform: string;\n conversationId: string;\n conversationKind: ConversationKind;\n userId: string;\n}\n\ntype EventToolParams = {\n action?: \"create\" | \"list\" | \"read\" | \"update\" | \"delete\";\n filename?: string;\n scope?: \"conversation\" | \"all\";\n label?: string;\n type?: \"immediate\" | \"one-shot\" | \"periodic\";\n text?: string;\n at?: string;\n schedule?: string;\n timezone?: string;\n filenamePrefix?: string;\n};\n\nexport type { EventPayload, EventStore } from \"./types.js\";\nimport type { EventPayload, EventStore } from \"./types.js\";\n\nexport class HostEventStore implements EventStore {\n constructor(private readonly eventsDir: string) {}\n\n static fromWorkspaceDir(workspaceDir: string): HostEventStore {\n return new HostEventStore(join(workspaceDir, \"events\"));\n }\n\n async write(filename: string, payload: EventPayload): Promise<{ path: string; size: number }> {\n return this.writePayload(filename, payload);\n }\n\n async list(): Promise<\n Array<{ filename: string; payload: EventPayload | null; size: number; mtimeMs: number }>\n > {\n await mkdir(this.eventsDir, { recursive: true });\n const entries = await readdir(this.eventsDir, { withFileTypes: true });\n const events = await Promise.all(\n entries\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".json\"))\n .map(async (entry) => {\n try {\n return await this.read(entry.name);\n } catch {\n // Keep unparseable files visible (payload: null) so consumers can\n // surface and delete them; skip files that vanished mid-listing.\n try {\n const fileStat = await stat(join(this.eventsDir, entry.name));\n return {\n filename: entry.name,\n payload: null,\n size: fileStat.size,\n mtimeMs: fileStat.mtimeMs,\n };\n } catch {\n return null;\n }\n }\n }),\n );\n return events\n .filter((event) => event !== null)\n .toSorted((a, b) => a.filename.localeCompare(b.filename));\n }\n\n async read(\n filename: string,\n ): Promise<{ filename: string; payload: EventPayload; size: number; mtimeMs: number }> {\n const safeFilename = validateEventFilename(filename);\n const filePath = join(this.eventsDir, safeFilename);\n const [raw, fileStat] = await Promise.all([readFile(filePath, \"utf-8\"), stat(filePath)]);\n // Validation (shape, per-type fields, channelId alias) is owned by the\n // event-format module; files that fail it surface as payload:null in\n // list() and as errors here.\n const payload = parseEventPayload(raw, safeFilename);\n return {\n filename: safeFilename,\n payload,\n size: fileStat.size,\n mtimeMs: fileStat.mtimeMs,\n };\n }\n\n async update(filename: string, payload: EventPayload): Promise<{ path: string; size: number }> {\n return this.writePayload(filename, payload, true);\n }\n\n async delete(filename: string): Promise<{ deleted: boolean }> {\n const safeFilename = validateEventFilename(filename);\n await rm(join(this.eventsDir, safeFilename), { force: true });\n return { deleted: true };\n }\n\n private async writePayload(\n filename: string,\n payload: EventPayload,\n requireExisting = false,\n ): Promise<{ path: string; size: number }> {\n await mkdir(this.eventsDir, { recursive: true });\n const safeFilename = validateEventFilename(filename);\n const filePath = join(this.eventsDir, safeFilename);\n if (requireExisting) {\n await stat(filePath);\n }\n atomicWritePrivateFile(filePath, JSON.stringify(payload) + \"\\n\");\n const fileStat = await stat(filePath);\n return { path: filePath, size: fileStat.size };\n }\n}\n\nexport function createEventTool(eventStore: EventStore): {\n tool: AgentTool<typeof eventSchema>;\n setEventContext: (context: EventToolContext) => void;\n} {\n let eventContext: EventToolContext | null = null;\n\n const tool: AgentTool<typeof eventSchema> = {\n name: \"event\",\n label: \"event\",\n description:\n \"CRUD tool for scheduled events. Create immediate, one-shot, or periodic events for the current conversation. List defaults to events for the current conversation only; use scope=all only when the user explicitly asks to list all events. Event text must be self-contained because events do not inherit normal conversation history.\",\n parameters: eventSchema,\n execute: async (_toolCallId: string, params: EventToolParams, signal?: AbortSignal) => {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n if (!eventContext) {\n throw new Error(\"Event context not configured\");\n }\n\n const action = params.action ?? \"create\";\n\n if (action === \"list\") {\n const events = await eventStore.list();\n const { conversationId, platform } = eventContext;\n const scopedEvents =\n params.scope === \"all\"\n ? events\n : events.filter(\n (event) =>\n event.payload?.conversationId === conversationId &&\n // Same raw id on another platform is another office. Files\n // written before payloads carried a platform stay visible.\n (event.payload.platform === undefined || event.payload.platform === platform),\n );\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(\n {\n scope: params.scope ?? \"conversation\",\n conversationId: params.scope === \"all\" ? undefined : conversationId,\n events: scopedEvents,\n },\n null,\n 2,\n ),\n },\n ],\n details: undefined,\n };\n }\n\n if (action === \"read\") {\n const filename = requireFilename(params);\n const event = await eventStore.read(filename);\n return {\n content: [{ type: \"text\", text: JSON.stringify(event, null, 2) }],\n details: undefined,\n };\n }\n\n if (action === \"delete\") {\n const filename = requireFilename(params);\n await eventStore.delete(filename);\n return {\n content: [{ type: \"text\", text: `Deleted event ${filename}` }],\n details: undefined,\n };\n }\n\n const payload = buildToolEventPayload(params, eventContext);\n const filename =\n action === \"update\"\n ? requireFilename(params)\n : `${sanitizeFileSegment(params.filenamePrefix || payload.type || \"event\")}-${Date.now()}.json`;\n\n log.logInfo(\n `${action === \"update\" ? \"Updating\" : \"Writing\"} event file via control plane store: ${filename} (type=${payload.type}, platform=${payload.platform}, conversation=${payload.conversationId})`,\n );\n\n try {\n const result =\n action === \"update\"\n ? await eventStore.update(filename, payload)\n : await eventStore.write(filename, payload);\n log.logInfo(\n `${action === \"update\" ? \"Updated\" : \"Wrote\"} event file via control plane store: ${result.path} (${result.size} bytes)`,\n );\n } catch (err) {\n log.logWarning(\n `Failed to ${action === \"update\" ? \"update\" : \"write\"} event file via control plane store: ${filename}`,\n String(err),\n );\n throw err;\n }\n\n return {\n content: [{ type: \"text\", text: formatEventWriteResult(action, filename, payload) }],\n details: undefined,\n };\n },\n };\n\n return {\n tool,\n setEventContext: (context: EventToolContext) => {\n eventContext = context;\n },\n };\n}\n\nfunction buildToolEventPayload(params: EventToolParams, context: EventToolContext): EventPayload {\n if (!params.type) {\n throw new Error(\"`type` is required for create and update actions\");\n }\n if (!params.text) {\n throw new Error(\"`text` is required for create and update actions\");\n }\n\n // Per-type field rules live in the event-format module. No sessionKey or\n // threadTs in the payload: reminders should fire as top-level messages,\n // not buried in old threads.\n const payload = buildEventPayload({\n type: params.type,\n platform: context.platform,\n conversationId: context.conversationId,\n conversationKind: context.conversationKind,\n userId: context.userId,\n text: params.text,\n at: params.at,\n schedule: params.schedule,\n timezone: params.timezone,\n });\n\n // Tool-side write policy, not format knowledge: a reminder in the past\n // would be deleted unfired by the watcher, so reject it here.\n if (payload.type === \"one-shot\" && new Date(payload.at).getTime() <= Date.now()) {\n throw new Error(\n `\\`at\\` must be in the future; got ${payload.at} (now=${new Date().toISOString()}). Check the timezone offset.`,\n );\n }\n\n return payload;\n}\n\nfunction formatEventWriteResult(\n action: \"create\" | \"update\",\n filename: string,\n payload: EventPayload,\n): string {\n const scheduledVerb = action === \"update\" ? \"Updated\" : \"Scheduled\";\n const immediateVerb = action === \"update\" ? \"Updated\" : \"Queued\";\n const target = payload.platform\n ? `${payload.platform}/${payload.conversationId}`\n : payload.conversationId;\n switch (payload.type) {\n case \"periodic\":\n return `${scheduledVerb} periodic event ${filename} for ${target} (${payload.schedule} ${payload.timezone})`;\n case \"one-shot\":\n return `${scheduledVerb} one-shot event ${filename} for ${target} at ${payload.at}`;\n case \"immediate\":\n return `${immediateVerb} immediate event ${filename} for ${target}`;\n }\n}\n\nfunction requireFilename(params: EventToolParams): string {\n if (!params.filename) {\n throw new Error(\"`filename` is required for read, update, and delete actions\");\n }\n return validateEventFilename(params.filename);\n}\n\nfunction validateEventFilename(filename: string): string {\n const trimmed = filename.trim();\n if (\n !trimmed ||\n trimmed !== basename(trimmed) ||\n trimmed.includes(\"..\") ||\n !trimmed.endsWith(\".json\")\n ) {\n throw new Error(\"Invalid event filename\");\n }\n return trimmed;\n}\n\nfunction sanitizeFileSegment(value: string): string {\n const sanitized = value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return sanitized || \"event\";\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Type } from "@sinclair/typebox";
|
|
2
|
-
import { writeFile } from "fs/promises";
|
|
3
|
-
import { join } from "path";
|
|
4
|
-
import { randomUUID } from "crypto";
|
|
2
|
+
import { writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
5
|
const schema = Type.Object({
|
|
6
6
|
prompt: Type.String({ description: "Description of the image to generate" }),
|
|
7
7
|
size: Type.Optional(Type.String({ description: "Requested image size, for example 1024x1024" })),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-image.js","sourceRoot":"","sources":["../../src/tools/generate-image.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"generate-image.js","sourceRoot":"","sources":["../../src/tools/generate-image.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;IACzB,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,sCAAsC,EAAE,CAAC;IAC5E,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,6CAA6C,EAAE,CAAC,CAAC;IAChG,OAAO,EAAE,IAAI,CAAC,QAAQ,CACpB,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,2DAA2D,EAAE,CAAC,CAC1F;CACF,CAAC,CAAC;AAOH,MAAM,UAAU,uBAAuB,CAAC,OAOvC;IAOC,IAAI,QAAQ,GAAiE,IAAI,CAAC;IAElF,OAAO;QACL,IAAI,EAAE;YACJ,IAAI,EAAE,gBAAgB;YACtB,KAAK,EAAE,gBAAgB;YACvB,WAAW,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I,GAAG,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAkB,CAAC;gBACtD,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;oBACjB,MAAM,IAAI,KAAK,CACb,gCAAgC,OAAO,CAAC,KAAK,CAAC,EAAE,YAAY;wBAC1D,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,IAAI,QAAQ,QAAQ,CAAC,MAAM,EAAE,CAAC,CACrD,CAAC;gBACJ,CAAC;gBACD,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC;gBACzC,IAAI,CAAC,OAAO;oBAAE,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;gBAE9E,MAAM,QAAQ,GAAG,aAAa,UAAU,EAAE,MAAM,CAAC;gBACjD,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;gBACnD,MAAM,SAAS,CAAC,QAAQ,EAAE,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC;gBAC1D,MAAM,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;gBAEnC,OAAO;oBACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,iCAAiC,QAAQ,EAAE,EAAE,CAAC;oBACvF,OAAO,EAAE,EAAE,QAAQ,EAAE;iBACtB,CAAC;YACJ,CAAC;SACF;QACD,iBAAiB,EAAE,CAAC,EAAE,EAAE,EAAE;YACxB,QAAQ,GAAG,EAAE,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { Api, Model } from \"@earendil-works/pi-ai\";\nimport { Type } from \"@sinclair/typebox\";\nimport { writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\n\nconst schema = Type.Object({\n prompt: Type.String({ description: \"Description of the image to generate\" }),\n size: Type.Optional(Type.String({ description: \"Requested image size, for example 1024x1024\" })),\n quality: Type.Optional(\n Type.String({ description: \"Requested image quality, for example low, medium, or high\" }),\n ),\n});\n\ninterface ImageResponse {\n data?: Array<{ b64_json?: string }>;\n error?: { message?: string };\n}\n\nexport function createGenerateImageTool(options: {\n model: Model<Api>;\n getApiKey: () => Promise<string | undefined>;\n /** Host directory the generated image is written into. Must be the\n * conversation's own office dir so the agent can also reach the file\n * from inside the sandbox; the workspace base is NOT guest-visible. */\n outputDir: string;\n}): {\n tool: AgentTool<typeof schema>;\n /** The callback receives the HOST path of the generated file. The image is\n * written host-side, so upload must not stage it through the sandbox the\n * way the attach tool does — the file may not be mounted there. */\n setUploadFunction: (fn: (hostPath: string, title?: string) => Promise<void>) => void;\n} {\n let uploadFn: ((hostPath: string, title?: string) => Promise<void>) | null = null;\n\n return {\n tool: {\n name: \"generate_image\",\n label: \"generate image\",\n description:\n \"Generate an image with the configured model provider and attach it to the response.\",\n parameters: schema,\n execute: async (_toolCallId, params, signal) => {\n if (!uploadFn) throw new Error(\"Upload function not configured\");\n if (!options.model.baseUrl)\n throw new Error(\"Image generation requires a configured model baseUrl\");\n const apiKey = await options.getApiKey();\n if (!apiKey) throw new Error(`No API key configured for ${options.model.provider}`);\n\n const response = await fetch(\n `${options.model.baseUrl.replace(/\\/$/, \"\")}/images/generations`,\n {\n method: \"POST\",\n signal,\n headers: {\n ...options.model.headers,\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n model: options.model.id,\n prompt: params.prompt,\n ...(params.size ? { size: params.size } : {}),\n ...(params.quality ? { quality: params.quality } : {}),\n response_format: \"b64_json\",\n }),\n },\n );\n const body = (await response.json()) as ImageResponse;\n if (!response.ok) {\n throw new Error(\n `Image generation with model \"${options.model.id}\" failed: ` +\n (body.error?.message ?? `HTTP ${response.status}`),\n );\n }\n const encoded = body.data?.[0]?.b64_json;\n if (!encoded) throw new Error(\"Image generation response contained no image\");\n\n const fileName = `generated-${randomUUID()}.png`;\n const filePath = join(options.outputDir, fileName);\n await writeFile(filePath, Buffer.from(encoded, \"base64\"));\n await uploadFn(filePath, fileName);\n\n return {\n content: [{ type: \"text\" as const, text: `Generated and attached image: ${fileName}` }],\n details: { fileName },\n };\n },\n },\n setUploadFunction: (fn) => {\n uploadFn = fn;\n },\n };\n}\n"]}
|
package/dist/tools/read.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Type } from "@sinclair/typebox";
|
|
2
|
-
import { extname } from "path";
|
|
3
|
-
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateHead, } from "
|
|
2
|
+
import { extname } from "node:path";
|
|
3
|
+
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateHead, } from "@earendil-works/pi-agent-core";
|
|
4
4
|
/**
|
|
5
5
|
* Map of file extensions to MIME types for common image formats
|
|
6
6
|
*/
|
|
@@ -36,7 +36,7 @@ const readSchema = Type.Object({
|
|
|
36
36
|
function trimToCharBoundary(buffer) {
|
|
37
37
|
for (let back = 1; back <= Math.min(4, buffer.length); back++) {
|
|
38
38
|
const byte = buffer[buffer.length - back];
|
|
39
|
-
if ((byte & 0xc0) === 0x80)
|
|
39
|
+
if (byte === undefined || (byte & 0xc0) === 0x80)
|
|
40
40
|
continue; // continuation byte; keep walking back
|
|
41
41
|
const needed = byte < 0x80 ? 1 : byte < 0xe0 ? 2 : byte < 0xf0 ? 3 : 4;
|
|
42
42
|
return back === needed ? buffer : buffer.subarray(0, buffer.length - back);
|
|
@@ -90,7 +90,7 @@ export function createReadTool(executor) {
|
|
|
90
90
|
// Serve the line in byte-addressed slices rather than pointing at
|
|
91
91
|
// another tool: the caller may not hold one (Session Dream grants only
|
|
92
92
|
// read/edit/write), and a dead end there costs a whole run.
|
|
93
|
-
const lineBuffer = Buffer.from(selectedContent.split("\n")[0], "utf-8");
|
|
93
|
+
const lineBuffer = Buffer.from(selectedContent.split("\n")[0] ?? "", "utf-8");
|
|
94
94
|
const start = Math.max(0, Math.min(byteOffset ?? 0, lineBuffer.length));
|
|
95
95
|
const slice = trimToCharBoundary(lineBuffer.subarray(start, start + DEFAULT_MAX_BYTES));
|
|
96
96
|
const end = start + slice.length;
|
package/dist/tools/read.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read.js","sourceRoot":"","sources":["../../src/tools/read.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAE/B,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,UAAU,EAEV,YAAY,GACb,MAAM,eAAe,CAAC;AAEvB;;GAEG;AACH,MAAM,gBAAgB,GAA2B;IAC/C,MAAM,EAAE,YAAY;IACpB,OAAO,EAAE,YAAY;IACrB,MAAM,EAAE,WAAW;IACnB,MAAM,EAAE,WAAW;IACnB,OAAO,EAAE,YAAY;CACtB,CAAC;AAEF;;GAEG;AACH,SAAS,WAAW,CAAC,QAAgB;IACnC,MAAM,GAAG,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,CAAC;IAC5C,OAAO,gBAAgB,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC;AACvC,CAAC;AAED,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;IAC7B,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC;QACjB,WAAW,EAAE,kEAAkE;KAChF,CAAC;IACF,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,iDAAiD,EAAE,CAAC;IACrF,MAAM,EAAE,IAAI,CAAC,QAAQ,CACnB,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,+CAA+C,EAAE,CAAC,CAC9E;IACD,KAAK,EAAE,IAAI,C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M,CAAC;gBACN,wCAAwC;gBACxC,UAAU,GAAG,UAAU,CAAC,OAAO,CAAC;YAClC,CAAC;YAED,OAAO;gBACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC;gBAC7C,OAAO;aACR,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai\";\nimport { Type } from \"@sinclair/typebox\";\nimport { extname } from \"path\";\nimport type { Executor } from \"../sandbox/index.js\";\nimport {\n DEFAULT_MAX_BYTES,\n DEFAULT_MAX_LINES,\n formatSize,\n type TruncationResult,\n truncateHead,\n} from \"./truncate.js\";\n\n/**\n * Map of file extensions to MIME types for common image formats\n */\nconst IMAGE_MIME_TYPES: Record<string, string> = {\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".png\": \"image/png\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n};\n\n/**\n * Check if a file is an image based on its extension\n */\nfunction isImageFile(filePath: string): string | null {\n const ext = extname(filePath).toLowerCase();\n return IMAGE_MIME_TYPES[ext] || null;\n}\n\nconst readSchema = Type.Object({\n label: Type.String({\n description: \"Brief description of what you're reading and why (shown to user)\",\n }),\n path: Type.String({ description: \"Path to the file to read (relative or absolute)\" }),\n offset: Type.Optional(\n Type.Number({ description: \"Line number to start reading from (1-indexed)\" }),\n ),\n limit: Type.Optional(Type.Number({ description: \"Maximum number of lines to read\" })),\n byteOffset: Type.Optional(\n Type.Number({\n description:\n \"Byte offset into the first selected line. Use to page through a line too large to return whole.\",\n }),\n ),\n});\n\n/**\n * Trim bytes that would split a multi-byte UTF-8 sequence at the slice end, so\n * paging through a long line never emits a replacement character at the seam.\n */\nfunction trimToCharBoundary(buffer: Buffer): Buffer {\n for (let back = 1; back <= Math.min(4, buffer.length); back++) {\n const byte = buffer[buffer.length - back];\n if ((byte & 0xc0) === 0x80) continue; // continuation byte; keep walking back\n const needed = byte < 0x80 ? 1 : byte < 0xe0 ? 2 : byte < 0xf0 ? 3 : 4;\n return back === needed ? buffer : buffer.subarray(0, buffer.length - back);\n }\n return buffer;\n}\n\ninterface ReadToolDetails {\n truncation?: TruncationResult;\n}\n\nexport function createReadTool(executor: Executor): AgentTool<typeof readSchema> {\n return {\n name: \"read\",\n label: \"read\",\n description: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files, and byteOffset to page through a single line larger than the byte limit.`,\n parameters: readSchema,\n execute: async (\n _toolCallId: string,\n {\n path,\n offset,\n limit,\n byteOffset,\n }: {\n label: string;\n path: string;\n offset?: number;\n limit?: number;\n byteOffset?: number;\n },\n signal?: AbortSignal,\n ): Promise<{\n content: (TextContent | ImageContent)[];\n details: ReadToolDetails | undefined;\n }> => {\n const mimeType = isImageFile(path);\n\n if (mimeType) {\n // Binary content rides the executor's own transport, never shell argv.\n const base64 = await executor.readFileBase64(path, { signal });\n\n return {\n content: [\n { type: \"text\", text: `Read image file [${mimeType}]` },\n { type: \"image\", data: base64, mimeType },\n ],\n details: undefined,\n };\n }\n\n // One transport read; line selection is plain code, not shell strings.\n const fileText = await executor.readFile(path, { signal });\n const fileLines = fileText.split(\"\\n\");\n const totalFileLines = fileLines.length;\n\n // Apply offset if specified (1-indexed)\n const startLine = offset ? Math.max(1, offset) : 1;\n const startLineDisplay = startLine;\n\n // Check if offset is out of bounds\n if (startLine > totalFileLines) {\n throw new Error(`Offset ${offset} is beyond end of file (${totalFileLines} lines total)`);\n }\n\n let selectedContent = startLine === 1 ? fileText : fileLines.slice(startLine - 1).join(\"\\n\");\n let userLimitedLines: number | undefined;\n\n // Apply user limit if specified\n if (limit !== undefined) {\n const lines = selectedContent.split(\"\\n\");\n const endLine = Math.min(limit, lines.length);\n selectedContent = lines.slice(0, endLine).join(\"\\n\");\n userLimitedLines = endLine;\n }\n\n // Apply truncation (respects both line and byte limits)\n const truncation = truncateHead(selectedContent);\n\n let outputText: string;\n let details: ReadToolDetails | undefined;\n\n if (truncation.firstLineExceedsLimit) {\n // Serve the line in byte-addressed slices rather than pointing at\n // another tool: the caller may not hold one (Session Dream grants only\n // read/edit/write), and a dead end there costs a whole run.\n const lineBuffer = Buffer.from(selectedContent.split(\"\\n\")[0], \"utf-8\");\n const start = Math.max(0, Math.min(byteOffset ?? 0, lineBuffer.length));\n const slice = trimToCharBoundary(lineBuffer.subarray(start, start + DEFAULT_MAX_BYTES));\n const end = start + slice.length;\n\n outputText = slice.toString(\"utf-8\");\n outputText += `\\n\\n[Line ${startLineDisplay} is ${formatSize(lineBuffer.length)}; showing bytes ${start}-${end}.`;\n outputText +=\n end < lineBuffer.length ? ` Use byteOffset=${end} to continue]` : \" End of line reached]\";\n details = { truncation };\n } else if (truncation.truncated) {\n // Truncation occurred - build actionable notice\n const endLineDisplay = startLineDisplay + truncation.outputLines - 1;\n const nextOffset = endLineDisplay + 1;\n\n outputText = truncation.content;\n\n if (truncation.truncatedBy === \"lines\") {\n outputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue]`;\n } else {\n outputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue]`;\n }\n details = { truncation };\n } else if (userLimitedLines !== undefined) {\n // User specified limit, check if there's more content\n const linesFromStart = startLine - 1 + userLimitedLines;\n if (linesFromStart < totalFileLines) {\n const remaining = totalFileLines - linesFromStart;\n const nextOffset = startLine + userLimitedLines;\n\n outputText = truncation.content;\n outputText += `\\n\\n[${remaining} more lines in file. Use offset=${nextOffset} to continue]`;\n } else {\n outputText = truncation.content;\n }\n } else {\n // No truncation, no user limit exceeded\n outputText = truncation.content;\n }\n\n return {\n content: [{ type: \"text\", text: outputText }],\n details,\n };\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"read.js","sourceRoot":"","sources":["../../src/tools/read.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,UAAU,EAEV,YAAY,GACb,MAAM,+BAA+B,CAAC;AAEvC;;GAEG;AACH,MAAM,gBAAgB,GAA2B;IAC/C,MAAM,EAAE,YAAY;IACpB,OAAO,EAAE,YAAY;IACrB,MAAM,EAAE,WAAW;IACnB,MAAM,EAAE,WAAW;IACnB,OAAO,EAAE,YAAY;CACtB,CAAC;AAEF;;GAEG;AACH,SAAS,WAAW,CAAC,QAAgB;IACnC,MAAM,GAAG,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,CAAC;IAC5C,OAAO,gBAAgB,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC;AACvC,CAAC;AAED,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;IAC7B,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC;QACjB,WAAW,EAAE,kEAAkE;KAChF,CAAC;IACF,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,iDAAiD,EAAE,CAAC;IACrF,MAAM,EAAE,IAAI,CAAC,QAAQ,CACnB,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,+CAA+C,EAAE,CAAC,CAC9E;IACD,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,iCAAiC,EAAE,CAAC,CAAC;IACrF,UAAU,EAAE,IAAI,CAAC,QAAQ,CACvB,IAAI,CAAC,MAAM,CAAC;QACV,WAAW,EACT,iGAAiG;KACpG,CAAC,CACH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AU,EAAE,CAAC;gBAC7C,OAAO;aACR,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai\";\nimport { Type } from \"@sinclair/typebox\";\nimport { extname } from \"node:path\";\nimport type { Executor } from \"../sandbox/index.js\";\nimport {\n DEFAULT_MAX_BYTES,\n DEFAULT_MAX_LINES,\n formatSize,\n type TruncationResult,\n truncateHead,\n} from \"@earendil-works/pi-agent-core\";\n\n/**\n * Map of file extensions to MIME types for common image formats\n */\nconst IMAGE_MIME_TYPES: Record<string, string> = {\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".png\": \"image/png\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n};\n\n/**\n * Check if a file is an image based on its extension\n */\nfunction isImageFile(filePath: string): string | null {\n const ext = extname(filePath).toLowerCase();\n return IMAGE_MIME_TYPES[ext] || null;\n}\n\nconst readSchema = Type.Object({\n label: Type.String({\n description: \"Brief description of what you're reading and why (shown to user)\",\n }),\n path: Type.String({ description: \"Path to the file to read (relative or absolute)\" }),\n offset: Type.Optional(\n Type.Number({ description: \"Line number to start reading from (1-indexed)\" }),\n ),\n limit: Type.Optional(Type.Number({ description: \"Maximum number of lines to read\" })),\n byteOffset: Type.Optional(\n Type.Number({\n description:\n \"Byte offset into the first selected line. Use to page through a line too large to return whole.\",\n }),\n ),\n});\n\n/**\n * Trim bytes that would split a multi-byte UTF-8 sequence at the slice end, so\n * paging through a long line never emits a replacement character at the seam.\n */\nfunction trimToCharBoundary(buffer: Buffer): Buffer {\n for (let back = 1; back <= Math.min(4, buffer.length); back++) {\n const byte = buffer[buffer.length - back];\n if (byte === undefined || (byte & 0xc0) === 0x80) continue; // continuation byte; keep walking back\n const needed = byte < 0x80 ? 1 : byte < 0xe0 ? 2 : byte < 0xf0 ? 3 : 4;\n return back === needed ? buffer : buffer.subarray(0, buffer.length - back);\n }\n return buffer;\n}\n\ninterface ReadToolDetails {\n truncation?: TruncationResult;\n}\n\nexport function createReadTool(executor: Executor): AgentTool<typeof readSchema> {\n return {\n name: \"read\",\n label: \"read\",\n description: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files, and byteOffset to page through a single line larger than the byte limit.`,\n parameters: readSchema,\n execute: async (\n _toolCallId: string,\n {\n path,\n offset,\n limit,\n byteOffset,\n }: {\n label: string;\n path: string;\n offset?: number;\n limit?: number;\n byteOffset?: number;\n },\n signal?: AbortSignal,\n ): Promise<{\n content: (TextContent | ImageContent)[];\n details: ReadToolDetails | undefined;\n }> => {\n const mimeType = isImageFile(path);\n\n if (mimeType) {\n // Binary content rides the executor's own transport, never shell argv.\n const base64 = await executor.readFileBase64(path, { signal });\n\n return {\n content: [\n { type: \"text\", text: `Read image file [${mimeType}]` },\n { type: \"image\", data: base64, mimeType },\n ],\n details: undefined,\n };\n }\n\n // One transport read; line selection is plain code, not shell strings.\n const fileText = await executor.readFile(path, { signal });\n const fileLines = fileText.split(\"\\n\");\n const totalFileLines = fileLines.length;\n\n // Apply offset if specified (1-indexed)\n const startLine = offset ? Math.max(1, offset) : 1;\n const startLineDisplay = startLine;\n\n // Check if offset is out of bounds\n if (startLine > totalFileLines) {\n throw new Error(`Offset ${offset} is beyond end of file (${totalFileLines} lines total)`);\n }\n\n let selectedContent = startLine === 1 ? fileText : fileLines.slice(startLine - 1).join(\"\\n\");\n let userLimitedLines: number | undefined;\n\n // Apply user limit if specified\n if (limit !== undefined) {\n const lines = selectedContent.split(\"\\n\");\n const endLine = Math.min(limit, lines.length);\n selectedContent = lines.slice(0, endLine).join(\"\\n\");\n userLimitedLines = endLine;\n }\n\n // Apply truncation (respects both line and byte limits)\n const truncation = truncateHead(selectedContent);\n\n let outputText: string;\n let details: ReadToolDetails | undefined;\n\n if (truncation.firstLineExceedsLimit) {\n // Serve the line in byte-addressed slices rather than pointing at\n // another tool: the caller may not hold one (Session Dream grants only\n // read/edit/write), and a dead end there costs a whole run.\n const lineBuffer = Buffer.from(selectedContent.split(\"\\n\")[0] ?? \"\", \"utf-8\");\n const start = Math.max(0, Math.min(byteOffset ?? 0, lineBuffer.length));\n const slice = trimToCharBoundary(lineBuffer.subarray(start, start + DEFAULT_MAX_BYTES));\n const end = start + slice.length;\n\n outputText = slice.toString(\"utf-8\");\n outputText += `\\n\\n[Line ${startLineDisplay} is ${formatSize(lineBuffer.length)}; showing bytes ${start}-${end}.`;\n outputText +=\n end < lineBuffer.length ? ` Use byteOffset=${end} to continue]` : \" End of line reached]\";\n details = { truncation };\n } else if (truncation.truncated) {\n // Truncation occurred - build actionable notice\n const endLineDisplay = startLineDisplay + truncation.outputLines - 1;\n const nextOffset = endLineDisplay + 1;\n\n outputText = truncation.content;\n\n if (truncation.truncatedBy === \"lines\") {\n outputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue]`;\n } else {\n outputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue]`;\n }\n details = { truncation };\n } else if (userLimitedLines !== undefined) {\n // User specified limit, check if there's more content\n const linesFromStart = startLine - 1 + userLimitedLines;\n if (linesFromStart < totalFileLines) {\n const remaining = totalFileLines - linesFromStart;\n const nextOffset = startLine + userLimitedLines;\n\n outputText = truncation.content;\n outputText += `\\n\\n[${remaining} more lines in file. Use offset=${nextOffset} to continue]`;\n } else {\n outputText = truncation.content;\n }\n } else {\n // No truncation, no user limit exceeded\n outputText = truncation.content;\n }\n\n return {\n content: [{ type: \"text\", text: outputText }],\n details,\n };\n },\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent.d.ts","sourceRoot":"","sources":["../../src/tools/subagent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAA2B,MAAM,+BAA+B,CAAC;AACxF,OAAO,EAAqB,KAAK,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,KAAK,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AA2HpG,QAAA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAA0B,CAAC;AAM/C,KAAK,WAAW,GAAG,CAAC,aAAa,SAAS,OAAO,GAAG,SAAS,GAAG,SAAS,EACvE,OAAO,EAAE,kBAAkB,CAAC,aAAa,CAAC,KACvC,OAAO,CAAC,iBAAiB,CAAC,iBAAiB,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"subagent.d.ts","sourceRoot":"","sources":["../../src/tools/subagent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAA2B,MAAM,+BAA+B,CAAC;AACxF,OAAO,EAAqB,KAAK,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,KAAK,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AA2HpG,QAAA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAA0B,CAAC;AAM/C,KAAK,WAAW,GAAG,CAAC,aAAa,SAAS,OAAO,GAAG,SAAS,GAAG,SAAS,EACvE,OAAO,EAAE,kBAAkB,CAAC,aAAa,CAAC,KACvC,OAAO,CAAC,iBAAiB,CAAC,iBAAiB,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;AAsSlE,gFAAgF;AAChF,UAAU,wBAAwB;IAChC,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;CAClB;AAyBD;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAChC,WAAW,EAAE,WAAW,EACxB,QAAQ,EAAE,WAAW,CAAC,MAAM,EAAE,wBAAwB,CAAC,GACtD,SAAS,CAAC,OAAO,cAAc,CAAC,CA8ElC"}
|
package/dist/tools/subagent.js
CHANGED
|
@@ -244,7 +244,10 @@ async function forEachConcurrent(items, limit, worker) {
|
|
|
244
244
|
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
245
245
|
while (cursor < items.length) {
|
|
246
246
|
const index = cursor++;
|
|
247
|
-
|
|
247
|
+
const item = items[index];
|
|
248
|
+
if (item === undefined)
|
|
249
|
+
continue;
|
|
250
|
+
await worker(item, index);
|
|
248
251
|
}
|
|
249
252
|
}));
|
|
250
253
|
}
|
|
@@ -391,7 +394,11 @@ export function createSubagentTool(runSubagent, profiles) {
|
|
|
391
394
|
};
|
|
392
395
|
}
|
|
393
396
|
case "single": {
|
|
394
|
-
const
|
|
397
|
+
const single = ordered[0];
|
|
398
|
+
if (single === undefined) {
|
|
399
|
+
throw new Error("Subagent plan produced no outcome");
|
|
400
|
+
}
|
|
401
|
+
const { id: _id, ...result } = single;
|
|
395
402
|
return {
|
|
396
403
|
content: [{ type: "text", text: formatOutcome(result) }],
|
|
397
404
|
details: result,
|