@oyasmi/pipiclaw 0.9.3 → 0.9.4-beta.2
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/dist/agent/builtin-commands.d.ts +19 -0
- package/dist/agent/builtin-commands.js +80 -0
- package/dist/agent/channel-runner.d.ts +20 -208
- package/dist/agent/channel-runner.js +167 -1188
- package/dist/agent/maintenance-context.d.ts +1 -1
- package/dist/agent/maintenance-context.js +1 -1
- package/dist/agent/prompt/manifest.d.ts +6 -1
- package/dist/agent/prompt/manifest.js +45 -64
- package/dist/agent/prompt/resources.d.ts +3 -0
- package/dist/agent/prompt/resources.js +11 -2
- package/dist/agent/runner-factory.d.ts +1 -43
- package/dist/agent/{command-extension.d.ts → session/command-extension.d.ts} +4 -0
- package/dist/agent/{command-extension.js → session/command-extension.js} +48 -35
- package/dist/agent/{type-guards.d.ts → session/event-guards.d.ts} +2 -2
- package/dist/agent/{type-guards.js → session/event-guards.js} +5 -1
- package/dist/agent/session/model-selection.d.ts +47 -0
- package/dist/agent/session/model-selection.js +99 -0
- package/dist/agent/{session-adapter.d.ts → session/session-adapter.d.ts} +21 -1
- package/dist/agent/session/session-adapter.js +159 -0
- package/dist/agent/{session-events.d.ts → session/session-events.d.ts} +9 -5
- package/dist/agent/{session-events.js → session/session-events.js} +24 -13
- package/dist/agent/session/session-host.d.ts +200 -0
- package/dist/agent/session/session-host.js +621 -0
- package/dist/agent/{session-resource-gate.js → session/session-resource-gate.js} +5 -3
- package/dist/agent/status-render.d.ts +0 -1
- package/dist/agent/status-render.js +4 -16
- package/dist/agent/{context-budget.js → turn/context-budget.js} +5 -1
- package/dist/agent/{progress-formatter.d.ts → turn/progress-formatter.d.ts} +4 -1
- package/dist/agent/{run-queue.d.ts → turn/run-queue.d.ts} +1 -1
- package/dist/agent/{run-queue.js → turn/run-queue.js} +10 -5
- package/dist/{memory → agent/turn}/task-digest.js +4 -4
- package/dist/agent/turn/turn-context.d.ts +14 -0
- package/dist/agent/turn/turn-context.js +64 -0
- package/dist/agent/turn/turn-error.d.ts +31 -0
- package/dist/agent/turn/turn-error.js +68 -0
- package/dist/agent/turn/turn-finish.d.ts +50 -0
- package/dist/agent/turn/turn-finish.js +188 -0
- package/dist/agent/turn/turn-input.d.ts +43 -0
- package/dist/agent/turn/turn-input.js +79 -0
- package/dist/agent/turn/turn-pipeline.d.ts +68 -0
- package/dist/agent/turn/turn-pipeline.js +257 -0
- package/dist/agent/{turn-prompt.d.ts → turn/turn-prompt.d.ts} +2 -2
- package/dist/agent/{turn-prompt.js → turn/turn-prompt.js} +6 -2
- package/dist/agent/{turn-recovery.js → turn/turn-recovery.js} +1 -1
- package/dist/agent/{turn-state.d.ts → turn/turn-state.d.ts} +1 -1
- package/dist/agent/types.d.ts +43 -2
- package/dist/agent/types.js +1 -1
- package/dist/{models/auth-cli.d.ts → app/auth-command.d.ts} +1 -1
- package/dist/{models/auth-cli.js → app/auth-command.js} +14 -10
- package/dist/{runtime/app-home.d.ts → app/home.d.ts} +6 -2
- package/dist/{runtime/app-home.js → app/home.js} +22 -75
- package/dist/{runtime → app}/proxy.js +4 -2
- package/dist/{app-services.d.ts → app/services.d.ts} +5 -5
- package/dist/{app-services.js → app/services.js} +17 -14
- package/dist/channel/channel-context.d.ts +12 -2
- package/dist/channel/channel-context.js +29 -2
- package/dist/channel/channel-event.d.ts +10 -2
- package/dist/channel/channel-event.js +1 -1
- package/dist/channel/channel-index.js +4 -1
- package/dist/{runtime/project-commands.d.ts → channel/commands.d.ts} +1 -1
- package/dist/{runtime/project-commands.js → channel/commands.js} +17 -16
- package/dist/channel/project-scope-store.js +1 -1
- package/dist/channel/store.js +4 -0
- package/dist/commands/catalog.d.ts +24 -7
- package/dist/commands/catalog.js +91 -44
- package/dist/commands/reply-limits.d.ts +6 -0
- package/dist/commands/reply-limits.js +24 -0
- package/dist/{runtime/report-commands.d.ts → commands/router.d.ts} +10 -3
- package/dist/{runtime/report-commands.js → commands/router.js} +6 -6
- package/dist/{settings.d.ts → config/settings.d.ts} +10 -10
- package/dist/{settings.js → config/settings.js} +11 -11
- package/dist/{tools/config.d.ts → config/tools.d.ts} +1 -2
- package/dist/{tools/config.js → config/tools.js} +5 -2
- package/dist/dingtalk/access-token.d.ts +12 -0
- package/dist/dingtalk/access-token.js +51 -0
- package/dist/dingtalk/api.d.ts +19 -0
- package/dist/dingtalk/api.js +67 -0
- package/dist/dingtalk/bot.d.ts +97 -0
- package/dist/dingtalk/bot.js +389 -0
- package/dist/dingtalk/cards.d.ts +56 -0
- package/dist/dingtalk/cards.js +318 -0
- package/dist/{runtime → dingtalk}/channel-queue.js +4 -1
- package/dist/dingtalk/config.d.ts +19 -0
- package/dist/dingtalk/config.js +95 -0
- package/dist/dingtalk/connection.d.ts +57 -0
- package/dist/dingtalk/connection.js +356 -0
- package/dist/dingtalk/conversation-meta.d.ts +16 -0
- package/dist/dingtalk/conversation-meta.js +77 -0
- package/dist/{runtime → dingtalk}/delivery.d.ts +6 -2
- package/dist/{runtime → dingtalk}/delivery.js +29 -15
- package/dist/dingtalk/handler.d.ts +90 -0
- package/dist/dingtalk/handler.js +1 -0
- package/dist/dingtalk/inbound.d.ts +66 -0
- package/dist/dingtalk/inbound.js +137 -0
- package/dist/dingtalk/media.d.ts +66 -0
- package/dist/dingtalk/media.js +214 -0
- package/dist/events/{event-commands.js → commands.js} +99 -45
- package/dist/events/parse.d.ts +14 -0
- package/dist/events/parse.js +114 -0
- package/dist/events/types.d.ts +93 -0
- package/dist/events/types.js +1 -0
- package/dist/events/{event-validation.d.ts → validation.d.ts} +14 -3
- package/dist/events/{event-validation.js → validation.js} +17 -9
- package/dist/events/watcher.d.ts +67 -0
- package/dist/events/{events.js → watcher.js} +63 -121
- package/dist/executor.js +2 -2
- package/dist/index.d.ts +6 -4
- package/dist/index.js +2 -2
- package/dist/jobs/launch.d.ts +42 -0
- package/dist/jobs/launch.js +118 -0
- package/dist/{agent/job-manager.d.ts → jobs/manager.d.ts} +1 -67
- package/dist/{agent/job-manager.js → jobs/manager.js} +34 -157
- package/dist/jobs/record.d.ts +55 -0
- package/dist/jobs/record.js +36 -0
- package/dist/log.d.ts +12 -2
- package/dist/log.js +26 -34
- package/dist/main.js +3 -3
- package/dist/memory/commands.js +29 -23
- package/dist/memory/lifecycle.js +26 -5
- package/dist/memory/maintenance-gates.d.ts +2 -2
- package/dist/memory/maintenance-state.js +4 -1
- package/dist/memory/maintenance-tuning.d.ts +15 -0
- package/dist/memory/maintenance-tuning.js +3 -0
- package/dist/memory/reflect-job.d.ts +2 -2
- package/dist/memory/reflect-job.js +4 -2
- package/dist/memory/scheduler.d.ts +3 -3
- package/dist/memory/scheduler.js +5 -2
- package/dist/memory/sidecar-worker.js +1 -1
- package/dist/memory/transcript.js +1 -1
- package/dist/{agent/model-fallback.d.ts → models/fallback.d.ts} +6 -6
- package/dist/{agent/model-fallback.js → models/fallback.js} +15 -28
- package/dist/models/login-identity.d.ts +2 -0
- package/dist/models/login-identity.js +83 -0
- package/dist/models/provider-login.d.ts +3 -1
- package/dist/models/provider-login.js +8 -2
- package/dist/models/reference.d.ts +20 -0
- package/dist/models/{utils.js → reference.js} +0 -48
- package/dist/models/{utils.d.ts → runtime.d.ts} +1 -16
- package/dist/models/runtime.js +52 -0
- package/dist/paths.d.ts +2 -0
- package/dist/paths.js +9 -0
- package/dist/playbooks/agent-delegation.md +2 -2
- package/dist/playbooks/catalog.d.ts +6 -2
- package/dist/playbooks/catalog.js +9 -6
- package/dist/runtime/bootstrap.d.ts +7 -17
- package/dist/runtime/bootstrap.js +70 -659
- package/dist/runtime/durable-dispatch.d.ts +43 -4
- package/dist/runtime/durable-dispatch.js +153 -3
- package/dist/runtime/inbound-images.d.ts +18 -0
- package/dist/runtime/inbound-images.js +51 -0
- package/dist/runtime/shutdown.d.ts +39 -0
- package/dist/runtime/shutdown.js +120 -0
- package/dist/runtime/stop-watchdog.d.ts +16 -0
- package/dist/runtime/stop-watchdog.js +32 -0
- package/dist/runtime/task-driver.d.ts +6 -4
- package/dist/runtime/task-driver.js +58 -23
- package/dist/runtime/task-migration.js +25 -8
- package/dist/runtime/task-spawn.d.ts +1 -1
- package/dist/runtime/task-spawn.js +13 -6
- package/dist/runtime/turn-handler.d.ts +47 -0
- package/dist/runtime/turn-handler.js +318 -0
- package/dist/runtime/turn-run.d.ts +52 -0
- package/dist/runtime/turn-run.js +318 -0
- package/dist/runtime/wake-coalescing.d.ts +18 -0
- package/dist/runtime/wake-coalescing.js +29 -0
- package/dist/security/block-message.d.ts +22 -1
- package/dist/security/block-message.js +66 -1
- package/dist/security/command-guard.js +4 -0
- package/dist/security/network.d.ts +2 -1
- package/dist/security/network.js +7 -2
- package/dist/security/path-guard-check.js +2 -2
- package/dist/security/path-guard.js +4 -0
- package/dist/security/types.d.ts +1 -2
- package/dist/security/types.js +1 -2
- package/dist/shared/exact-keys.d.ts +1 -1
- package/dist/shared/format.d.ts +12 -0
- package/dist/shared/format.js +37 -0
- package/dist/shared/host-process.js +16 -4
- package/dist/shared/wake-claim.d.ts +1 -1
- package/dist/shared/with-timeout.d.ts +3 -2
- package/dist/shared/with-timeout.js +14 -3
- package/dist/{runtime/skill-commands.d.ts → skills/commands.d.ts} +2 -2
- package/dist/{runtime/skill-commands.js → skills/commands.js} +18 -11
- package/dist/{agent/workspace-resources.js → skills/loader.js} +1 -1
- package/dist/{tools/skill-security.js → skills/validation.js} +4 -0
- package/dist/skills/workspace.d.ts +33 -0
- package/dist/skills/workspace.js +116 -0
- package/dist/{runtime/subagent-commands.d.ts → subagents/commands.d.ts} +9 -7
- package/dist/{runtime/subagent-commands.js → subagents/commands.js} +116 -77
- package/dist/subagents/completion-wake.d.ts +17 -0
- package/dist/subagents/completion-wake.js +76 -0
- package/dist/subagents/detached-discovery.js +1 -1
- package/dist/subagents/discovery.d.ts +1 -1
- package/dist/subagents/discovery.js +2 -2
- package/dist/subagents/dispatch.d.ts +33 -0
- package/dist/subagents/dispatch.js +190 -0
- package/dist/subagents/external/claude-code.js +23 -1
- package/dist/subagents/external/dispatch.d.ts +25 -0
- package/dist/subagents/external/dispatch.js +90 -0
- package/dist/subagents/external/harness.d.ts +1 -1
- package/dist/subagents/external/progress-tail.d.ts +18 -1
- package/dist/subagents/external/progress-tail.js +64 -17
- package/dist/subagents/external/run.d.ts +5 -1
- package/dist/subagents/external/run.js +23 -9
- package/dist/subagents/external/settlement.d.ts +4 -1
- package/dist/subagents/external/settlement.js +1 -1
- package/dist/subagents/format.d.ts +1 -1
- package/dist/subagents/grace.d.ts +24 -0
- package/dist/subagents/grace.js +57 -0
- package/dist/subagents/internal/outcome.d.ts +24 -0
- package/dist/subagents/internal/outcome.js +149 -0
- package/dist/subagents/internal/provider-retry.d.ts +19 -0
- package/dist/subagents/internal/provider-retry.js +83 -0
- package/dist/subagents/internal/run.d.ts +31 -0
- package/dist/subagents/internal/run.js +240 -0
- package/dist/subagents/internal/state.d.ts +43 -0
- package/dist/subagents/internal/state.js +48 -0
- package/dist/subagents/internal/worker.d.ts +51 -0
- package/dist/subagents/internal/worker.js +167 -0
- package/dist/subagents/result.d.ts +62 -0
- package/dist/subagents/result.js +103 -0
- package/dist/subagents/run-record.d.ts +222 -0
- package/dist/subagents/run-record.js +101 -0
- package/dist/subagents/run-registry.d.ts +9 -0
- package/dist/subagents/run-registry.js +125 -0
- package/dist/subagents/runs.d.ts +16 -232
- package/dist/subagents/runs.js +132 -310
- package/dist/subagents/task-envelope.d.ts +36 -0
- package/dist/subagents/task-envelope.js +168 -0
- package/dist/subagents/types.d.ts +154 -0
- package/dist/subagents/types.js +1 -0
- package/dist/subagents/verification-outcome.d.ts +1 -1
- package/dist/subagents/workspace-summary.d.ts +16 -4
- package/dist/subagents/workspace-summary.js +74 -18
- package/dist/tasks/board.d.ts +10 -3
- package/dist/tasks/board.js +38 -3
- package/dist/tasks/{work-log.d.ts → bound-work.d.ts} +1 -1
- package/dist/tasks/{work-log.js → bound-work.js} +1 -1
- package/dist/tasks/brief.js +1 -1
- package/dist/{runtime/task-commands.d.ts → tasks/commands.d.ts} +1 -1
- package/dist/{runtime/task-commands.js → tasks/commands.js} +117 -67
- package/dist/tasks/contract-input.d.ts +1 -1
- package/dist/tasks/contract-input.js +1 -1
- package/dist/tasks/create.js +1 -1
- package/dist/tasks/frontmatter.d.ts +5 -0
- package/dist/tasks/frontmatter.js +8 -0
- package/dist/tasks/{log.d.ts → loop-log.d.ts} +11 -1
- package/dist/tasks/{log.js → loop-log.js} +59 -3
- package/dist/tasks/mutation-lock.js +1 -1
- package/dist/tasks/session-path.js +1 -1
- package/dist/tasks/steer.js +1 -1
- package/dist/tasks/store.js +6 -4
- package/dist/tasks/ticket.d.ts +3 -1
- package/dist/tasks/ticket.js +19 -1
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/bash.js +2 -2
- package/dist/tools/{tool-details.d.ts → contract/details.d.ts} +11 -3
- package/dist/tools/{tool-details.js → contract/details.js} +42 -5
- package/dist/tools/{presentation.js → contract/presentation.js} +3 -3
- package/dist/tools/event-manage.d.ts +1 -1
- package/dist/tools/event-manage.js +4 -4
- package/dist/tools/index.d.ts +5 -3
- package/dist/tools/index.js +8 -6
- package/dist/tools/job.d.ts +1 -1
- package/dist/tools/memory-manage.js +4 -1
- package/dist/tools/registry.d.ts +7 -7
- package/dist/tools/registry.js +6 -6
- package/dist/tools/session-search.d.ts +1 -1
- package/dist/tools/skill.d.ts +2 -34
- package/dist/tools/skill.js +8 -116
- package/dist/tools/subagent-manage.d.ts +1 -1
- package/dist/tools/subagent-manage.js +19 -13
- package/dist/tools/subagent.d.ts +46 -0
- package/dist/tools/subagent.js +127 -0
- package/dist/tools/{task-manage.d.ts → task-manage/factory.d.ts} +7 -3
- package/dist/tools/{task-manage.js → task-manage/factory.js} +7 -7
- package/dist/tools/task-manage/lifecycle.js +2 -2
- package/dist/tools/task-manage/log-view.js +2 -2
- package/dist/tools/task-manage/shared.js +3 -3
- package/dist/tools/task-manage/step-end.js +7 -4
- package/dist/tools/task-manage/types.d.ts +1 -1
- package/dist/tools/web-fetch.d.ts +1 -1
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/tui/app.d.ts +1 -1
- package/dist/tui/app.js +6 -6
- package/dist/tui/cli.d.ts +1 -1
- package/dist/tui/cli.js +3 -3
- package/dist/tui/commands.js +4 -4
- package/dist/tui/frontend.d.ts +44 -0
- package/dist/tui/frontend.js +13 -0
- package/dist/tui/pitui-frontend.d.ts +1 -1
- package/dist/tui/pitui-frontend.js +1 -1
- package/dist/tui/plain-frontend.d.ts +1 -1
- package/dist/tui/renderer.d.ts +3 -42
- package/dist/tui/renderer.js +3 -2
- package/dist/tui/terminal-context.d.ts +2 -2
- package/dist/tui/terminal-media-sender.d.ts +1 -1
- package/dist/tui/turn-controller.d.ts +3 -1
- package/dist/tui/turn-controller.js +36 -21
- package/dist/usage/ledger.js +7 -1
- package/dist/usage/render.js +3 -1
- package/dist/{shared/types.d.ts → usage/totals.d.ts} +3 -0
- package/dist/web/client.d.ts +5 -1
- package/dist/web/client.js +4 -0
- package/dist/web/config.d.ts +1 -1
- package/dist/web/fetch.d.ts +1 -1
- package/dist/web/search-providers.d.ts +1 -1
- package/dist/web/search.d.ts +1 -1
- package/package.json +9 -7
- package/dist/agent/session-adapter.js +0 -77
- package/dist/events/events.d.ts +0 -159
- package/dist/runtime/dingtalk.d.ts +0 -272
- package/dist/runtime/dingtalk.js +0 -1416
- package/dist/subagents/tool.d.ts +0 -206
- package/dist/subagents/tool.js +0 -1088
- /package/dist/{runtime → agent/prompt}/workspace-templates.d.ts +0 -0
- /package/dist/{runtime → agent/prompt}/workspace-templates.js +0 -0
- /package/dist/agent/{session-resource-gate.d.ts → session/session-resource-gate.d.ts} +0 -0
- /package/dist/agent/{context-budget.d.ts → turn/context-budget.d.ts} +0 -0
- /package/dist/agent/{progress-formatter.js → turn/progress-formatter.js} +0 -0
- /package/dist/{memory → agent/turn}/task-digest.d.ts +0 -0
- /package/dist/agent/{turn-recovery.d.ts → turn/turn-recovery.d.ts} +0 -0
- /package/dist/agent/{turn-state.js → turn/turn-state.js} +0 -0
- /package/dist/{runtime → app}/proxy.d.ts +0 -0
- /package/dist/{runtime → dingtalk}/channel-queue.d.ts +0 -0
- /package/dist/{runtime → dingtalk}/inbound-media.d.ts +0 -0
- /package/dist/{runtime → dingtalk}/inbound-media.js +0 -0
- /package/dist/events/{event-commands.d.ts → commands.d.ts} +0 -0
- /package/dist/{agent/workspace-resources.d.ts → skills/loader.d.ts} +0 -0
- /package/dist/{tools/skill-security.d.ts → skills/validation.d.ts} +0 -0
- /package/dist/tasks/{ledger.d.ts → contract.d.ts} +0 -0
- /package/dist/tasks/{ledger.js → contract.js} +0 -0
- /package/dist/tools/{subagent-tool-names.d.ts → contract/names.d.ts} +0 -0
- /package/dist/tools/{subagent-tool-names.js → contract/names.js} +0 -0
- /package/dist/tools/{presentation.d.ts → contract/presentation.d.ts} +0 -0
- /package/dist/{shared/types.js → usage/totals.js} +0 -0
|
@@ -9,77 +9,10 @@ import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
|
9
9
|
import { shellEscape } from "../shared/os.js";
|
|
10
10
|
import { createSerialQueue } from "../shared/serial-queue.js";
|
|
11
11
|
import { errorMessage } from "../shared/text-utils.js";
|
|
12
|
-
import { isRecord } from "../shared/type-guards.js";
|
|
13
12
|
import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
|
|
14
|
-
import { logTaskDispatch, logTaskSettlement } from "../tasks/work
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
spillFile,
|
|
18
|
-
exitFile: `${spillFile}.exit`,
|
|
19
|
-
exitTmp: `${spillFile}.exit.tmp`,
|
|
20
|
-
readyFile: `${spillFile}.ready`,
|
|
21
|
-
readyTmp: `${spillFile}.ready.tmp`,
|
|
22
|
-
metaFile: `${spillFile}.meta`,
|
|
23
|
-
metaTmp: `${spillFile}.meta.tmp`,
|
|
24
|
-
};
|
|
25
|
-
}
|
|
26
|
-
/** ~2s of readiness polling: 40 iterations of a 50ms sleep in the wrapper shell. */
|
|
27
|
-
const LAUNCH_HANDSHAKE_MAX_POLLS = 40;
|
|
28
|
-
/**
|
|
29
|
-
* Build the wrapper shell that launches a background job with a verifiable startup handshake.
|
|
30
|
-
*
|
|
31
|
-
* The inner shell writes an atomic `ready` marker as its very first action — *before* the user
|
|
32
|
-
* command — so the parent can distinguish "wrapper live, spill writable, command about to run"
|
|
33
|
-
* from "launch silently failed" (a read-only spill dir, a `setsid`/`sh` that could not exec). The
|
|
34
|
-
* parent also writes a metadata file (pid, and under `setsid` the pgid/start-time) *before* it
|
|
35
|
-
* waits on the handshake, so an abort that lands mid-handshake still leaves a recoverable pid.
|
|
36
|
-
*
|
|
37
|
-
* `setsid` (when present) makes the job its own session/process-group leader (pgid == pid), so a
|
|
38
|
-
* later cancel/timeout can terminate the whole group. A host without it falls back to `nohup` —
|
|
39
|
-
* still detached and restart-safe, but single-pid, so pgid/identity are deliberately not claimed.
|
|
40
|
-
*
|
|
41
|
-
* On handshake success the parent prints `MODE`/`PID`(/`PGID`/`LSTART`) and exits 0. On failure it
|
|
42
|
-
* kills whatever it spawned, echoes the inner error, removes the scratch files, and exits 1.
|
|
43
|
-
*/
|
|
44
|
-
function buildLaunchScript(command, art) {
|
|
45
|
-
const spill = shellEscape(art.spillFile);
|
|
46
|
-
const exitFile = shellEscape(art.exitFile);
|
|
47
|
-
const exitTmp = shellEscape(art.exitTmp);
|
|
48
|
-
const ready = shellEscape(art.readyFile);
|
|
49
|
-
const readyTmp = shellEscape(art.readyTmp);
|
|
50
|
-
const meta = shellEscape(art.metaFile);
|
|
51
|
-
const metaTmp = shellEscape(art.metaTmp);
|
|
52
|
-
// Subshell around the user command so its own `exit N` only leaves the subshell and the
|
|
53
|
-
// exit-capture still runs; the exit code is written temp-then-renamed so a probe never reads a
|
|
54
|
-
// half-written `.exit`.
|
|
55
|
-
const inner = `printf 'ready\\n' > ${readyTmp} && mv -f ${readyTmp} ${ready} || exit 127; ` +
|
|
56
|
-
`( ${command} )\n__pc_rc=$?; ` +
|
|
57
|
-
`printf '%s\\n' "$__pc_rc" > ${exitTmp} && mv -f ${exitTmp} ${exitFile}`;
|
|
58
|
-
const escInner = shellEscape(inner);
|
|
59
|
-
// `ps` can momentarily miss a just-forked process on a loaded host: one short retry.
|
|
60
|
-
const psField = (field) => `"$(ps -o ${field}= -p "$__pc_pid" 2>/dev/null || { sleep 0.1; ps -o ${field}= -p "$__pc_pid" 2>/dev/null; })"`;
|
|
61
|
-
const handshake = (killExpr) => `__pc_i=0; while [ ! -s ${ready} ] && [ "$__pc_i" -lt ${LAUNCH_HANDSHAKE_MAX_POLLS} ]; do ` +
|
|
62
|
-
`sleep 0.05; __pc_i=$((__pc_i+1)); done; ` +
|
|
63
|
-
`if [ ! -s ${ready} ]; then ${killExpr}printf 'HANDSHAKE failed\\n'; cat ${spill} 2>/dev/null; ` +
|
|
64
|
-
`rm -f ${ready} ${readyTmp} ${meta} ${metaTmp} ${exitFile} ${exitTmp} ${spill}; exit 1; fi`;
|
|
65
|
-
const setsidKill = `kill -TERM "-$__pc_pid" 2>/dev/null; kill -TERM "$__pc_pid" 2>/dev/null; sleep 0.1; ` +
|
|
66
|
-
`kill -KILL "-$__pc_pid" 2>/dev/null; `;
|
|
67
|
-
const nohupKill = `kill -TERM "$__pc_pid" 2>/dev/null; sleep 0.1; kill -KILL "$__pc_pid" 2>/dev/null; `;
|
|
68
|
-
const setsidBranch = `setsid sh -c ${escInner} > ${spill} 2>&1 & __pc_pid=$!; ` +
|
|
69
|
-
`__pc_pgid=$(printf '%s' ${psField("pgid")} | tr -d ' '); __pc_lstart=${psField("lstart")}; ` +
|
|
70
|
-
`printf 'MODE setsid\\nPID %s\\nPGID %s\\nLSTART %s\\n' "$__pc_pid" "$__pc_pgid" "$__pc_lstart" ` +
|
|
71
|
-
`> ${metaTmp} && mv -f ${metaTmp} ${meta}; ` +
|
|
72
|
-
`${handshake(setsidKill)}; ` +
|
|
73
|
-
`printf 'MODE setsid\\nPID %s\\nPGID %s\\nLSTART %s\\n' "$__pc_pid" "$__pc_pgid" "$__pc_lstart"`;
|
|
74
|
-
const nohupBranch = `nohup sh -c ${escInner} > ${spill} 2>&1 & __pc_pid=$!; ` +
|
|
75
|
-
`printf 'MODE nohup\\nPID %s\\n' "$__pc_pid" > ${metaTmp} && mv -f ${metaTmp} ${meta}; ` +
|
|
76
|
-
`${handshake(nohupKill)}; ` +
|
|
77
|
-
`printf 'MODE nohup\\nPID %s\\n' "$__pc_pid"`;
|
|
78
|
-
// `umask 077`: the spill holds whatever the command printed (routinely credentials) in a
|
|
79
|
-
// world-readable /tmp; set the mask rather than chmod afterwards so there is no readable window.
|
|
80
|
-
return (`umask 077; rm -f ${exitFile} ${exitTmp} ${ready} ${readyTmp} ${meta} ${metaTmp}; ` +
|
|
81
|
-
`if command -v setsid >/dev/null 2>&1; then ${setsidBranch}; else ${nohupBranch}; fi`);
|
|
82
|
-
}
|
|
13
|
+
import { logTaskDispatch, logTaskSettlement } from "../tasks/bound-work.js";
|
|
14
|
+
import { buildLaunchScript, jobArtifacts, parseLaunchOutput } from "./launch.js";
|
|
15
|
+
import { isTerminal, parseJobRecord, toSnapshot } from "./record.js";
|
|
83
16
|
/** Outcomes that prove the job's process is gone — safe to apply a terminal status. */
|
|
84
17
|
const KILL_CONFIRMED_GONE = new Set([
|
|
85
18
|
"terminated",
|
|
@@ -113,69 +46,6 @@ const JOB_OUTPUT_READ_MAX_BYTES = 512 * 1024;
|
|
|
113
46
|
function jobSpillPath(id, spillDir) {
|
|
114
47
|
return join(spillDir ?? tmpdir(), `pipiclaw-job-${id}.log`);
|
|
115
48
|
}
|
|
116
|
-
function isTerminal(status) {
|
|
117
|
-
return status !== "running";
|
|
118
|
-
}
|
|
119
|
-
/** Accept a persisted record only if the fields the manager actually relies on are intact. */
|
|
120
|
-
function parseJobRecord(raw) {
|
|
121
|
-
const value = JSON.parse(raw);
|
|
122
|
-
if (!isRecord(value) ||
|
|
123
|
-
typeof value.id !== "string" ||
|
|
124
|
-
typeof value.pid !== "number" ||
|
|
125
|
-
typeof value.spillFile !== "string" ||
|
|
126
|
-
typeof value.exitFile !== "string" ||
|
|
127
|
-
typeof value.startedAt !== "number" ||
|
|
128
|
-
typeof value.timeoutSeconds !== "number" ||
|
|
129
|
-
!isRecord(value.contract)) {
|
|
130
|
-
return undefined;
|
|
131
|
-
}
|
|
132
|
-
return value;
|
|
133
|
-
}
|
|
134
|
-
/**
|
|
135
|
-
* Read the launch command's stdout: an optional `MODE setsid|nohup` line followed by `PID <n>`
|
|
136
|
-
* and — only in `setsid` mode — `PGID <n>` / `LSTART <...>`. A bare number on its own line is also
|
|
137
|
-
* accepted as the pid so older/simpler executor fakes keep working. `pgid` and `pidStartedAt` are
|
|
138
|
-
* returned only when the job was launched under `setsid` *and* `ps` actually reported them; the
|
|
139
|
-
* `nohup` fallback never yields them, and the caller must then treat identity as unprovable.
|
|
140
|
-
*/
|
|
141
|
-
function parseLaunchOutput(stdout) {
|
|
142
|
-
let pid;
|
|
143
|
-
let pgid;
|
|
144
|
-
let pidStartedAt;
|
|
145
|
-
let mode;
|
|
146
|
-
let handshakeFailed = false;
|
|
147
|
-
for (const raw of stdout.split("\n")) {
|
|
148
|
-
const line = raw.trim();
|
|
149
|
-
if (!line)
|
|
150
|
-
continue;
|
|
151
|
-
if (line === "HANDSHAKE failed") {
|
|
152
|
-
handshakeFailed = true;
|
|
153
|
-
continue;
|
|
154
|
-
}
|
|
155
|
-
if (/^\d+$/.test(line)) {
|
|
156
|
-
pid ??= Number.parseInt(line, 10);
|
|
157
|
-
continue;
|
|
158
|
-
}
|
|
159
|
-
const match = line.match(/^(MODE|PID|PGID|LSTART)\s+(.*)$/);
|
|
160
|
-
if (!match)
|
|
161
|
-
continue;
|
|
162
|
-
const [, key, value] = match;
|
|
163
|
-
if (key === "MODE" && (value === "setsid" || value === "nohup"))
|
|
164
|
-
mode = value;
|
|
165
|
-
else if (key === "PID" && /^\d+$/.test(value))
|
|
166
|
-
pid = Number.parseInt(value, 10);
|
|
167
|
-
else if (key === "PGID" && /^\d+$/.test(value))
|
|
168
|
-
pgid = Number.parseInt(value, 10);
|
|
169
|
-
else if (key === "LSTART" && value)
|
|
170
|
-
pidStartedAt = value;
|
|
171
|
-
}
|
|
172
|
-
// The nohup fallback cannot capture these reliably; drop them even if something printed them.
|
|
173
|
-
if (mode === "nohup") {
|
|
174
|
-
pgid = undefined;
|
|
175
|
-
pidStartedAt = undefined;
|
|
176
|
-
}
|
|
177
|
-
return { pid, pgid, pidStartedAt, mode, handshakeFailed };
|
|
178
|
-
}
|
|
179
49
|
function sleep(ms, signal) {
|
|
180
50
|
return new Promise((resolve) => {
|
|
181
51
|
const timer = setTimeout(resolve, ms);
|
|
@@ -185,19 +55,6 @@ function sleep(ms, signal) {
|
|
|
185
55
|
}, { once: true });
|
|
186
56
|
});
|
|
187
57
|
}
|
|
188
|
-
function toSnapshot(record) {
|
|
189
|
-
return {
|
|
190
|
-
id: record.id,
|
|
191
|
-
label: record.label,
|
|
192
|
-
command: record.command,
|
|
193
|
-
status: record.status,
|
|
194
|
-
startedAt: record.startedAt,
|
|
195
|
-
durationMs: record.status === "running" ? Date.now() - record.startedAt : record.durationMs,
|
|
196
|
-
exitCode: record.exitCode,
|
|
197
|
-
timeoutSeconds: record.timeoutSeconds,
|
|
198
|
-
taskId: record.contract.taskId,
|
|
199
|
-
};
|
|
200
|
-
}
|
|
201
58
|
export class ChannelJobManager {
|
|
202
59
|
constructor(channelId, executor, options = {}) {
|
|
203
60
|
this.channelId = channelId;
|
|
@@ -235,7 +92,10 @@ export class ChannelJobManager {
|
|
|
235
92
|
catch (error) {
|
|
236
93
|
if (required)
|
|
237
94
|
throw error;
|
|
238
|
-
log.
|
|
95
|
+
log.logWarn("job.persist.failed", "Background job persist failed", {
|
|
96
|
+
reason: errorMessage(error),
|
|
97
|
+
fields: { jobId: record.id },
|
|
98
|
+
});
|
|
239
99
|
}
|
|
240
100
|
}
|
|
241
101
|
async forget(record) {
|
|
@@ -416,7 +276,10 @@ export class ChannelJobManager {
|
|
|
416
276
|
agent: "job",
|
|
417
277
|
label,
|
|
418
278
|
}).catch((error) => {
|
|
419
|
-
log.
|
|
279
|
+
log.logWarn("job.task_dispatch.log_failed", "Task dispatch record failed", {
|
|
280
|
+
reason: errorMessage(error),
|
|
281
|
+
fields: { jobId: id, taskId: options.taskId },
|
|
282
|
+
});
|
|
420
283
|
});
|
|
421
284
|
}
|
|
422
285
|
this.ensureSweeper();
|
|
@@ -484,7 +347,7 @@ export class ChannelJobManager {
|
|
|
484
347
|
// rejection here (a probe that cannot spawn — EAGAIN/EMFILE/ENOMEM) exits the
|
|
485
348
|
// whole daemon, since nothing installs a process-level rejection handler.
|
|
486
349
|
this.sweep().catch((error) => {
|
|
487
|
-
log.
|
|
350
|
+
log.logWarn("job.sweep.failed", "Background job sweep failed", { reason: errorMessage(error) });
|
|
488
351
|
});
|
|
489
352
|
}, this.sweepIntervalMs);
|
|
490
353
|
// Do not keep the process alive just for the sweeper.
|
|
@@ -524,7 +387,10 @@ export class ChannelJobManager {
|
|
|
524
387
|
await this.applyProbe(record, probes.get(record.id) ?? "");
|
|
525
388
|
})
|
|
526
389
|
.catch((error) => {
|
|
527
|
-
log.
|
|
390
|
+
log.logWarn("job.sweep.refresh_failed", "Background job refresh failed", {
|
|
391
|
+
reason: errorMessage(error),
|
|
392
|
+
fields: { jobId: record.id },
|
|
393
|
+
});
|
|
528
394
|
});
|
|
529
395
|
}
|
|
530
396
|
await this.collectGarbage();
|
|
@@ -713,7 +579,10 @@ export class ChannelJobManager {
|
|
|
713
579
|
tail: output?.text.slice(-WAKE_OUTPUT_TAIL_BYTES).trim() || undefined,
|
|
714
580
|
durationMs: record.durationMs,
|
|
715
581
|
}).catch((error) => {
|
|
716
|
-
log.
|
|
582
|
+
log.logWarn("job.task_settle.log_failed", "Task settlement record failed", {
|
|
583
|
+
reason: errorMessage(error),
|
|
584
|
+
fields: { jobId: record.id, taskId },
|
|
585
|
+
});
|
|
717
586
|
});
|
|
718
587
|
await this.persist(record);
|
|
719
588
|
}
|
|
@@ -763,7 +632,10 @@ export class ChannelJobManager {
|
|
|
763
632
|
await this.options.dispatch(event);
|
|
764
633
|
}
|
|
765
634
|
catch (error) {
|
|
766
|
-
log.
|
|
635
|
+
log.logWarn("job.wake.dispatch_failed", "Completion wake dispatch failed", {
|
|
636
|
+
reason: errorMessage(error),
|
|
637
|
+
fields: { jobId: record.id },
|
|
638
|
+
});
|
|
767
639
|
return;
|
|
768
640
|
}
|
|
769
641
|
record.notified = true;
|
|
@@ -972,7 +844,9 @@ export class ChannelJobManager {
|
|
|
972
844
|
record = undefined;
|
|
973
845
|
}
|
|
974
846
|
if (!record) {
|
|
975
|
-
log.
|
|
847
|
+
log.logWarn("job.record.unreadable", "Unreadable background job record discarded", {
|
|
848
|
+
fields: { file: filename },
|
|
849
|
+
});
|
|
976
850
|
await unlink(path).catch(() => undefined);
|
|
977
851
|
continue;
|
|
978
852
|
}
|
|
@@ -981,7 +855,10 @@ export class ChannelJobManager {
|
|
|
981
855
|
// One probe decides between "still running", "finished while we were down", and "gone";
|
|
982
856
|
// refresh already encodes all three, including the late completion wake.
|
|
983
857
|
await this.refresh(record, signal).catch((error) => {
|
|
984
|
-
log.
|
|
858
|
+
log.logWarn("job.reconcile.failed", "Background job reconcile failed", {
|
|
859
|
+
reason: errorMessage(error),
|
|
860
|
+
fields: { jobId: record?.id },
|
|
861
|
+
});
|
|
985
862
|
});
|
|
986
863
|
}
|
|
987
864
|
await this.collectGarbage();
|
|
@@ -1019,7 +896,7 @@ export function createJobRuntime(executor, options = {}) {
|
|
|
1019
896
|
const manager = managers.get(channelId);
|
|
1020
897
|
if (!manager)
|
|
1021
898
|
return [];
|
|
1022
|
-
return manager.listRunning().map((job) =>
|
|
899
|
+
return manager.listRunning().map((job) => `后台作业 \`${job.id}\` 仍在运行:${job.command.slice(0, 80)}`);
|
|
1023
900
|
}
|
|
1024
901
|
function get(channelId) {
|
|
1025
902
|
let manager = managers.get(channelId);
|
|
@@ -1057,7 +934,7 @@ export function createJobRuntime(executor, options = {}) {
|
|
|
1057
934
|
.map((entry) => entry.name);
|
|
1058
935
|
}
|
|
1059
936
|
catch (error) {
|
|
1060
|
-
log.
|
|
937
|
+
log.logWarn("job.scan.failed", "Persisted background job scan failed", { reason: errorMessage(error) });
|
|
1061
938
|
return 0;
|
|
1062
939
|
}
|
|
1063
940
|
let restored = 0;
|
|
@@ -1065,7 +942,7 @@ export function createJobRuntime(executor, options = {}) {
|
|
|
1065
942
|
restored += await get(channelId).restore();
|
|
1066
943
|
}
|
|
1067
944
|
if (restored > 0) {
|
|
1068
|
-
log.
|
|
945
|
+
log.logInfoEvent("job.restore.done", "Background job records restored", { fields: { count: restored } });
|
|
1069
946
|
}
|
|
1070
947
|
return restored;
|
|
1071
948
|
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
export type JobStatus = "running" | "completed" | "failed" | "cancelled" | "lost";
|
|
2
|
+
export interface JobSnapshot {
|
|
3
|
+
id: string;
|
|
4
|
+
label: string;
|
|
5
|
+
command: string;
|
|
6
|
+
status: JobStatus;
|
|
7
|
+
startedAt: number;
|
|
8
|
+
durationMs: number;
|
|
9
|
+
exitCode?: number;
|
|
10
|
+
/** The job's own wall-clock limit; a task's `work` ticket derives its backstop from it. */
|
|
11
|
+
timeoutSeconds: number;
|
|
12
|
+
/** The task this job's completion wake belongs to, if any — lets a caller verify that a
|
|
13
|
+
* `[JOB:<id>] ... belongs to task <taskId>.` wake actually names the job it claims to (T9). */
|
|
14
|
+
taskId?: string;
|
|
15
|
+
}
|
|
16
|
+
/** What should happen when the job finishes. */
|
|
17
|
+
export interface JobWakeContract {
|
|
18
|
+
/** Wake the channel on completion. Defaults to true — that is the point of the mechanism. */
|
|
19
|
+
notify: boolean;
|
|
20
|
+
/** The task this job is advancing, surfaced in the wake so the model lands in context. */
|
|
21
|
+
taskId?: string;
|
|
22
|
+
}
|
|
23
|
+
export interface JobRecord extends JobSnapshot {
|
|
24
|
+
pid: number;
|
|
25
|
+
/** Process-group id of the launched job, as `ps` reported it right after spawn. `setsid` makes
|
|
26
|
+
* the job its own session/group leader, so this normally equals `pid` — the precondition for a
|
|
27
|
+
* safe negative-PGID kill. Absent on records written before this was captured. */
|
|
28
|
+
pgid?: number;
|
|
29
|
+
/** `ps -o lstart=` for `pid` at launch: the only OS-verifiable way to tell the still-running
|
|
30
|
+
* job apart from an unrelated process that later reused its pid. Absent on older records and
|
|
31
|
+
* whenever `ps` was unavailable at launch — callers must then treat identity as unprovable. */
|
|
32
|
+
pidStartedAt?: string;
|
|
33
|
+
spillFile: string;
|
|
34
|
+
exitFile: string;
|
|
35
|
+
timeoutSeconds: number;
|
|
36
|
+
contract: JobWakeContract;
|
|
37
|
+
/** When the job reached a terminal status; drives retention of the record and spill file. */
|
|
38
|
+
finishedAt?: number;
|
|
39
|
+
/** Set once the completion wake has been dispatched, so a restart cannot re-announce it. */
|
|
40
|
+
notified?: boolean;
|
|
41
|
+
/** Set once the owning task's log has this job's settlement (spec 052, D4); guards against a second record. */
|
|
42
|
+
taskLogged?: boolean;
|
|
43
|
+
/**
|
|
44
|
+
* A cancel or timeout whose kill could not be *confirmed* yet: the job stays `running` and
|
|
45
|
+
* manageable, and every sweep re-attempts the kill until the process is proven gone, at which
|
|
46
|
+
* point this terminal status is applied. Internal only — never surfaced in a `JobSnapshot`.
|
|
47
|
+
*/
|
|
48
|
+
pendingKill?: "cancelled" | "failed";
|
|
49
|
+
wakeClaimDispatchId?: string;
|
|
50
|
+
wakeConsumedAt?: number;
|
|
51
|
+
}
|
|
52
|
+
export declare function isTerminal(status: JobStatus): boolean;
|
|
53
|
+
/** Accept a persisted record only if the fields the manager actually relies on are intact. */
|
|
54
|
+
export declare function parseJobRecord(raw: string): JobRecord | undefined;
|
|
55
|
+
export declare function toSnapshot(record: JobRecord): JobSnapshot;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Background-job record vocabulary: status, the snapshot handed to callers, the persisted record
|
|
3
|
+
* and its parser. No state and no I/O, shared by the job manager and its tool/callers (spec 054 D11).
|
|
4
|
+
*/
|
|
5
|
+
import { isRecord } from "../shared/type-guards.js";
|
|
6
|
+
export function isTerminal(status) {
|
|
7
|
+
return status !== "running";
|
|
8
|
+
}
|
|
9
|
+
/** Accept a persisted record only if the fields the manager actually relies on are intact. */
|
|
10
|
+
export function parseJobRecord(raw) {
|
|
11
|
+
const value = JSON.parse(raw);
|
|
12
|
+
if (!isRecord(value) ||
|
|
13
|
+
typeof value.id !== "string" ||
|
|
14
|
+
typeof value.pid !== "number" ||
|
|
15
|
+
typeof value.spillFile !== "string" ||
|
|
16
|
+
typeof value.exitFile !== "string" ||
|
|
17
|
+
typeof value.startedAt !== "number" ||
|
|
18
|
+
typeof value.timeoutSeconds !== "number" ||
|
|
19
|
+
!isRecord(value.contract)) {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
export function toSnapshot(record) {
|
|
25
|
+
return {
|
|
26
|
+
id: record.id,
|
|
27
|
+
label: record.label,
|
|
28
|
+
command: record.command,
|
|
29
|
+
status: record.status,
|
|
30
|
+
startedAt: record.startedAt,
|
|
31
|
+
durationMs: record.status === "running" ? Date.now() - record.startedAt : record.durationMs,
|
|
32
|
+
exitCode: record.exitCode,
|
|
33
|
+
timeoutSeconds: record.timeoutSeconds,
|
|
34
|
+
taskId: record.contract.taskId,
|
|
35
|
+
};
|
|
36
|
+
}
|
package/dist/log.d.ts
CHANGED
|
@@ -38,8 +38,18 @@ export declare function logResponseStart(ctx: LogContext): void;
|
|
|
38
38
|
export declare function logThinking(ctx: LogContext, thinking: string): void;
|
|
39
39
|
export declare function logResponse(ctx: LogContext, text: string): void;
|
|
40
40
|
export declare function logInfo(message: string, details?: string): void;
|
|
41
|
-
export
|
|
41
|
+
export interface EventLogOptions {
|
|
42
|
+
channelId?: string;
|
|
43
|
+
/** Why it happened (an error message, a rejection). Kept out of `message` so the message stays greppable. */
|
|
44
|
+
reason?: string;
|
|
45
|
+
/** Ids and counts the event is about. */
|
|
46
|
+
fields?: Record<string, unknown>;
|
|
47
|
+
}
|
|
48
|
+
export declare function logWarn(event: string, message: string, options?: EventLogOptions): void;
|
|
49
|
+
export declare function logInfoEvent(event: string, message: string, options?: EventLogOptions): void;
|
|
50
|
+
export declare function logDebugEvent(event: string, message: string, options?: EventLogOptions): void;
|
|
42
51
|
export declare function logModelFallback(ctx: LogContext, from: string, to: string, error: string): void;
|
|
52
|
+
/** One structured record per turn's usage; the context fill rides along when known. */
|
|
43
53
|
export declare function logUsageSummary(ctx: LogContext, usage: {
|
|
44
54
|
input: number;
|
|
45
55
|
output: number;
|
|
@@ -52,6 +62,6 @@ export declare function logUsageSummary(ctx: LogContext, usage: {
|
|
|
52
62
|
cacheWrite: number;
|
|
53
63
|
total: number;
|
|
54
64
|
};
|
|
55
|
-
}, contextTokens?: number, contextWindow?: number):
|
|
65
|
+
}, contextTokens?: number, contextWindow?: number): void;
|
|
56
66
|
export declare function logStartup(workingDir: string): void;
|
|
57
67
|
export declare function logConnected(): void;
|
package/dist/log.js
CHANGED
|
@@ -216,9 +216,11 @@ export function logResponse(ctx, text) {
|
|
|
216
216
|
});
|
|
217
217
|
}
|
|
218
218
|
// Compatibility helpers keep lower-risk call sites centralized while they use
|
|
219
|
-
// the same output contract as structured events.
|
|
219
|
+
// the same output contract as structured events. The channel prefix accepts any non-blank id:
|
|
220
|
+
// a group channel is `group_<conversationId>`, and DingTalk conversation ids are base64 (`+`, `/`,
|
|
221
|
+
// `=`), which a word-character class silently failed to match — group logs lost their `channel`.
|
|
220
222
|
function legacyContext(message) {
|
|
221
|
-
const match = /^\[([
|
|
223
|
+
const match = /^\[([^\]\s]+)\]\s*/.exec(message);
|
|
222
224
|
return match ? { message: message.slice(match[0].length), ctx: { channelId: match[1] } } : { message };
|
|
223
225
|
}
|
|
224
226
|
export function logInfo(message, details) {
|
|
@@ -228,43 +230,33 @@ export function logInfo(message, details) {
|
|
|
228
230
|
...(details ? { details, fields: { reason: details } } : {}),
|
|
229
231
|
});
|
|
230
232
|
}
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
233
|
+
/**
|
|
234
|
+
* One runtime event with a filterable `<domain>.<object>.<verb>` name (spec 053, D12). `message`
|
|
235
|
+
* is a fixed sentence (`<Subject> failed`); what varies goes to `reason` and `fields`, which the
|
|
236
|
+
* console line and the JSONL record both carry.
|
|
237
|
+
*/
|
|
238
|
+
function logNamedEvent(level, event, message, options) {
|
|
239
|
+
const fields = { ...options.fields, ...(options.reason ? { reason: options.reason } : {}) };
|
|
240
|
+
logEvent(level, event, message, {
|
|
241
|
+
...(options.channelId ? { ctx: { channelId: options.channelId } } : {}),
|
|
242
|
+
...(options.reason ? { details: options.reason } : {}),
|
|
243
|
+
...(Object.keys(fields).length > 0 ? { fields } : {}),
|
|
236
244
|
});
|
|
237
245
|
}
|
|
246
|
+
export function logWarn(event, message, options = {}) {
|
|
247
|
+
logNamedEvent("warn", event, message, options);
|
|
248
|
+
}
|
|
249
|
+
export function logInfoEvent(event, message, options = {}) {
|
|
250
|
+
logNamedEvent("info", event, message, options);
|
|
251
|
+
}
|
|
252
|
+
export function logDebugEvent(event, message, options = {}) {
|
|
253
|
+
logNamedEvent("debug", event, message, options);
|
|
254
|
+
}
|
|
238
255
|
export function logModelFallback(ctx, from, to, error) {
|
|
239
256
|
logEvent("warn", "agent.model.fallback", "Using fallback model", { ctx, fields: { from, to, error } });
|
|
240
257
|
}
|
|
258
|
+
/** One structured record per turn's usage; the context fill rides along when known. */
|
|
241
259
|
export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
|
|
242
|
-
const formatTokens = (count) => {
|
|
243
|
-
if (count < 1000)
|
|
244
|
-
return count.toString();
|
|
245
|
-
if (count < 10000)
|
|
246
|
-
return `${(count / 1000).toFixed(1)}k`;
|
|
247
|
-
if (count < 1000000)
|
|
248
|
-
return `${Math.round(count / 1000)}k`;
|
|
249
|
-
return `${(count / 1000000).toFixed(1)}M`;
|
|
250
|
-
};
|
|
251
|
-
const lines = [
|
|
252
|
-
"**Usage Summary**",
|
|
253
|
-
`Tokens: ${usage.input.toLocaleString()} in, ${usage.output.toLocaleString()} out`,
|
|
254
|
-
...(usage.cacheRead > 0 || usage.cacheWrite > 0
|
|
255
|
-
? [`Cache: ${usage.cacheRead.toLocaleString()} read, ${usage.cacheWrite.toLocaleString()} write`]
|
|
256
|
-
: []),
|
|
257
|
-
...(contextTokens && contextWindow
|
|
258
|
-
? [
|
|
259
|
-
`Context: ${formatTokens(contextTokens)} / ${formatTokens(contextWindow)} (${((contextTokens / contextWindow) * 100).toFixed(1)}%)`,
|
|
260
|
-
]
|
|
261
|
-
: []),
|
|
262
|
-
`Cost: $${usage.cost.input.toFixed(4)} in, $${usage.cost.output.toFixed(4)} out` +
|
|
263
|
-
(usage.cacheRead > 0 || usage.cacheWrite > 0
|
|
264
|
-
? `, $${usage.cost.cacheRead.toFixed(4)} cache read, $${usage.cost.cacheWrite.toFixed(4)} cache write`
|
|
265
|
-
: ""),
|
|
266
|
-
`**Total: $${usage.cost.total.toFixed(4)}** (incl. sub-agents)`,
|
|
267
|
-
];
|
|
268
260
|
logEvent("info", "agent.usage", "Usage recorded", {
|
|
269
261
|
ctx,
|
|
270
262
|
fields: {
|
|
@@ -273,9 +265,9 @@ export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
|
|
|
273
265
|
cacheRead: usage.cacheRead,
|
|
274
266
|
cacheWrite: usage.cacheWrite,
|
|
275
267
|
cost: usage.cost,
|
|
268
|
+
...(contextTokens && contextWindow ? { contextTokens, contextWindow } : {}),
|
|
276
269
|
},
|
|
277
270
|
});
|
|
278
|
-
return lines.join("\n");
|
|
279
271
|
}
|
|
280
272
|
export function logStartup(workingDir) {
|
|
281
273
|
logEvent("info", "runtime.started", "Starting pipiclaw", { fields: { workingDir } });
|
package/dist/main.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { runAuth } from "./app/auth-command.js";
|
|
3
|
+
import { formatCliCommandsHelp, isBootstrapExitError } from "./app/home.js";
|
|
2
4
|
import * as log from "./log.js";
|
|
3
|
-
import { runAuth } from "./models/auth-cli.js";
|
|
4
|
-
import { formatCliCommandsHelp, isBootstrapExitError } from "./runtime/app-home.js";
|
|
5
5
|
import { bootstrap } from "./runtime/bootstrap.js";
|
|
6
6
|
import { errorMessage } from "./shared/text-utils.js";
|
|
7
7
|
import { runTui } from "./tui/cli.js";
|
|
@@ -62,6 +62,6 @@ else {
|
|
|
62
62
|
console.error(`Unknown command: ${command}`);
|
|
63
63
|
for (const line of formatCliCommandsHelp("pipiclaw"))
|
|
64
64
|
console.error(line);
|
|
65
|
-
console.error("Run `pipiclaw --help` for
|
|
65
|
+
console.error("Run `pipiclaw --help` for usage.");
|
|
66
66
|
process.exit(1);
|
|
67
67
|
}
|
package/dist/memory/commands.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { renderSubcommandUsage } from "../commands/catalog.js";
|
|
2
|
-
import { capReply } from "../commands/reply-limits.js";
|
|
2
|
+
import { capReply, flattenMarkdownForChat } from "../commands/reply-limits.js";
|
|
3
3
|
import { localDayKey } from "../shared/local-time.js";
|
|
4
4
|
import { getDefaultChannelMemoryQueue } from "./channel-maintenance-queue.js";
|
|
5
5
|
import { buildChannelIndexForBootstrap, CHANNEL_INDEX_MAX_UNITS } from "./index-budget.js";
|
|
@@ -32,10 +32,10 @@ async function handleStatus(options) {
|
|
|
32
32
|
"**记忆状态**",
|
|
33
33
|
"",
|
|
34
34
|
`- 频道条目:\`${entries.length}\`(${MEMORY_TYPE_ORDER.map((type) => `${type} ${byType.get(type) ?? 0}`).join(" / ")})`,
|
|
35
|
-
`-
|
|
36
|
-
`-
|
|
37
|
-
`-
|
|
38
|
-
`-
|
|
35
|
+
`- 观察期条目:\`${probationary.length}\`${probationary.length > 0 ? `(最早到期 \`${probationary[0].expires}\`)` : ""}`,
|
|
36
|
+
`- 文件头解析异常:\`${malformed.length}\`${malformed.length > 0 ? `(${malformed.map((e) => e.name).join("、")})` : ""}`,
|
|
37
|
+
`- 上次后台整理:\`${state?.lastReflectAt ?? "从未"}\``,
|
|
38
|
+
`- 索引大小:${tiered.overBudget ? "超出预算,注入时优先带最近更新的条目;下次整理会尝试合并" : "未超出预算,整份注入"}`,
|
|
39
39
|
].join("\n");
|
|
40
40
|
}
|
|
41
41
|
async function handleList(options, typeArg) {
|
|
@@ -45,10 +45,12 @@ async function handleList(options, typeArg) {
|
|
|
45
45
|
const entries = await listMemoryEntries(options.channelDir);
|
|
46
46
|
const filtered = typeArg ? entries.filter((entry) => entry.type === typeArg) : entries;
|
|
47
47
|
if (filtered.length === 0) {
|
|
48
|
-
return typeArg
|
|
48
|
+
return typeArg
|
|
49
|
+
? `暂无 \`${typeArg}\` 类型的记忆。\n用 \`/memory list\` 查看全部。`
|
|
50
|
+
: "暂无生效的频道记忆。\n在对话里告诉我需要长期记住的事,我会保存下来。";
|
|
49
51
|
}
|
|
50
52
|
const lines = filtered.map((entry) => {
|
|
51
|
-
const marker = entry.body.trim() ? "
|
|
53
|
+
const marker = entry.body.trim() ? "(有正文)" : "";
|
|
52
54
|
const probation = entry.expires ? `(观察期至 \`${entry.expires}\`)` : "";
|
|
53
55
|
return `- \`${entry.name}\` [${entry.type}]${probation} ${entry.description}${marker}`;
|
|
54
56
|
});
|
|
@@ -58,32 +60,34 @@ async function handleList(options, typeArg) {
|
|
|
58
60
|
}
|
|
59
61
|
async function handleShow(options, name) {
|
|
60
62
|
if (!name)
|
|
61
|
-
return
|
|
63
|
+
return `缺少记忆名称。\n\n${renderUsage()}`;
|
|
62
64
|
const entry = await readMemoryEntry(options.channelDir, name);
|
|
63
65
|
if (!entry)
|
|
64
66
|
return `未找到记忆 \`${name}\`。用 \`/memory list\` 查看可用名称。`;
|
|
67
|
+
// Frontmatter keys stay visible (the user sees them when opening the file), introduced by a
|
|
68
|
+
// Chinese label rather than shown bare (spec 053, D1).
|
|
65
69
|
const lines = [
|
|
66
70
|
`**记忆 ${name}**`,
|
|
67
71
|
"",
|
|
68
|
-
`- type
|
|
69
|
-
`- source
|
|
70
|
-
`- created
|
|
72
|
+
`- 类型(type):\`${entry.type}\``,
|
|
73
|
+
`- 来源(source):\`${entry.source}\``,
|
|
74
|
+
`- 创建(created):\`${entry.created}\`;更新(updated):\`${entry.updated}\``,
|
|
71
75
|
];
|
|
72
76
|
if (entry.expires)
|
|
73
|
-
lines.push(`- expires
|
|
77
|
+
lines.push(`- 观察期至(expires):\`${entry.expires}\``);
|
|
74
78
|
if (entry.malformed)
|
|
75
|
-
lines.push("- ⚠️
|
|
79
|
+
lines.push("- ⚠️ 文件头解析异常,以第一段作为描述");
|
|
76
80
|
lines.push("", entry.description);
|
|
77
81
|
if (entry.body.trim())
|
|
78
|
-
lines.push("", entry.body.trim());
|
|
79
|
-
return lines.join("\n");
|
|
82
|
+
lines.push("", flattenMarkdownForChat(entry.body.trim()));
|
|
83
|
+
return capReply(lines.join("\n"), { nextStepHint: "完整内容在频道目录的 `memory/` 下" }).text;
|
|
80
84
|
}
|
|
81
85
|
async function handleForget(options, name) {
|
|
82
86
|
if (!name)
|
|
83
|
-
return
|
|
87
|
+
return `缺少记忆名称。\n\n${renderUsage()}`;
|
|
84
88
|
const entry = await readMemoryEntry(options.channelDir, name);
|
|
85
89
|
if (!entry)
|
|
86
|
-
return `未找到记忆 \`${name}
|
|
90
|
+
return `未找到记忆 \`${name}\`,未做任何改动。用 \`/memory list\` 查看可用名称。`;
|
|
87
91
|
await getDefaultChannelMemoryQueue().run(options.channelId, () => applyMemoryOps(options.channelDir, [{ op: "delete", name, reason: "/memory forget" }]));
|
|
88
92
|
await appendMemoryReviewLog(options.channelDir, {
|
|
89
93
|
timestamp: new Date().toISOString(),
|
|
@@ -91,20 +95,22 @@ async function handleForget(options, name) {
|
|
|
91
95
|
reason: "memory-forget",
|
|
92
96
|
actions: [{ op: "forget", name, contentHash: hashMemoryContent(entry.description) }],
|
|
93
97
|
}).catch(() => { });
|
|
94
|
-
return `已删除 \`${name}
|
|
98
|
+
return `已删除 \`${name}\`,并记入忽略名单,后台整理不会再自动写回;你之后重新说起这件事,仍然可以被记住。`;
|
|
95
99
|
}
|
|
96
100
|
async function handleJournal(options, dateArg) {
|
|
97
101
|
const date = dateArg ?? localDayKey();
|
|
98
102
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
|
|
99
|
-
return `日期格式应为 \`YYYY-MM-DD
|
|
103
|
+
return `日期格式应为 \`YYYY-MM-DD\`。\n\n${renderUsage()}`;
|
|
100
104
|
}
|
|
101
105
|
const content = await readJournalDay(options.channelDir, date);
|
|
102
106
|
if (!content.trim()) {
|
|
103
107
|
const dates = await listJournalDates(options.channelDir);
|
|
104
|
-
const hint = dates.length > 0
|
|
105
|
-
|
|
108
|
+
const hint = dates.length > 0
|
|
109
|
+
? `有记录的日期:${dates.slice(-10).join("、")}`
|
|
110
|
+
: "工作日记由后台整理按天写入,有对话之后会出现。";
|
|
111
|
+
return `暂无 ${date} 的工作日记。\n${hint}`;
|
|
106
112
|
}
|
|
107
|
-
return capReply(
|
|
113
|
+
return capReply(`**工作日记 ${date}**\n\n${flattenMarkdownForChat(content.trim())}`, {
|
|
108
114
|
nextStepHint: "用 `/memory journal <YYYY-MM-DD>` 查看其他日期",
|
|
109
115
|
}).text;
|
|
110
116
|
}
|
|
@@ -120,5 +126,5 @@ export async function handleMemoryCommand(options) {
|
|
|
120
126
|
return handleForget(options, argument);
|
|
121
127
|
if (action === "journal")
|
|
122
128
|
return handleJournal(options, argument);
|
|
123
|
-
return
|
|
129
|
+
return `未知子命令 \`${action}\`。\n\n${renderUsage()}`;
|
|
124
130
|
}
|