{"modulePath":"github.com/flashcatcloud/flashduty-runner","version":"v0.0.27","isLatest":true,"isStandardLibrary":false,"goos":"linux","goarch":"amd64","docs":"# package environment\n\nPackage workspace implements local workspace operations.\n\nHTML→Markdown / HTML→Text conversion helpers used by webfetch.\n\nInlined from go-pkg/x/htmlx — keep in sync. flashduty-runner is open-source and may not import internal flashcatcloud modules.\n\nSSRF guard for outbound HTTP. Runner pods must NEVER reach IMDS or the cluster apiserver from inside; without dial-time IP validation a prompt-injected URL can exfiltrate cloud credentials from 169.254.169.254 or hit internal VPC services. The DNS-to-dial re-resolution closes the DNS-rebinding gap a host-string allowlist would leave open.\n\nInlined from go-pkg/x/netsafe — keep in sync. flashduty-runner is open-source and may not import internal flashcatcloud modules.\n\n## Constants\n\n```go\nconst (\n\t// DefaultMaxOutputSize is the default character limit before truncation.\n\t// 50000 chars (~12.5k tokens at 4 chars/token) matches Claude Code's\n\t// DEFAULT_MAX_RESULT_SIZE_CHARS spill threshold — the point at which a tool\n\t// result is persisted to a file and the agent gets a preview + path.\n\tDefaultMaxOutputSize = 50000\n\t// DefaultPreviewSize is the maximum characters for preview\n\tDefaultPreviewSize = 8000 // ~2k tokens\n\t// DefaultPreviewLines is the number of lines shown in the preview\n\tDefaultPreviewLines = 20\n\t// OutputsDir is the directory name for storing large outputs\n\tOutputsDir = \".outputs\"\n)\n```\n\n```go\nconst BrokerSupported = true\n```\nBrokerSupported reports whether this build can run the egress broker.\n\n## Variables\n\n```go\nvar ErrOutputCapped = errors.New(\"output capped\")\n```\nErrOutputCapped is returned by LimitedWriter once its byte cap has been reached. Surfaces the contract violation that would otherwise be hidden by the writer pretending it accepted everything (\\`return len(p), nil\\`).\n\n## Functions\n\n```go\nfunc BashToolEnv() []string\n```\nBashToolEnv returns the exact base environment every bash tool subprocess runs with: ambient Flashduty secrets scrubbed, and the bundled-tools dir prepended to PATH so OUR fduty resolves. Per-call extraEnv (e.g. the bash guard re-supplying credentials) is layered on top by the caller. Startup's fduty self-check uses this so it validates the real call-time PATH, not an approximation.\n\n```go\nfunc BrokerEgressEnabled() bool\n```\nBrokerEgressEnabled reports whether this runner should advertise egress-broker support to safari. Two conditions must both hold:\n\n 1. this build can run the broker (BrokerSupported — Linux only), and\n 2. the bundled fduty can act as a broker-mode client.\n\nCondition 2 is load-bearing: once safari sees broker=1 it delivers the per-person app\\_key out-of-band over the inherited control fd and NEVER in the bash env. An older bundled fduty that doesn't understand FLASHDUTY\\_CRED\\_FD would then have no usable key and every authenticated call would fail. The runner does not refresh fduty on self-update, so a fleet runner can carry a stale fduty across a runner upgrade. Gating the advertisement here makes the rollout self-healing: a stale fduty keeps the legacy env-key path, and once it is updated the next reconnect advertises broker mode. It also works in zero-egress BYOC, where the runner cannot fetch a newer fduty.\n\nThe fduty probe runs at most once and is cached; its cost is a single \\`fduty version --json\\`.\n\n```go\nfunc BundledToolsDir() string\n```\nBundledToolsDir returns the directory holding the CLIs the runner ships with it — the flashduty CLI in particular. Bash subprocesses must resolve OUR bundled flashduty rather than whatever a BYOC host happens to have earlier on PATH (a different version, or an unrelated binary of the same name).\n\nThe same value serves two roles that MUST NOT diverge: the dir we prepend to every bash subprocess's PATH (so fduty resolves), and the dir we install fduty into (FLASHDUTY\\_INSTALL\\_DIR in provision.go). If the PATH dir is read-only, install.sh relocates fduty to ~/.local/bin — which is not on the bash PATH — and every \\`fduty\\` call 127s. To make divergence impossible by construction, the default is a runner-owned, guaranteed-writable directory under the runner's state home: \\\u003cstate home\u003e/bin, where the state home is the same root the runner uses for its workspace (FLASHDUTY\\_RUNNER\\_HOME, with the deprecated FLASHDUTY\\_RUNNER\\_WORKSPACE alias, falling back to ~/.flashduty). Under the systemd unit that root sits inside ReadWritePaths, so it is writable even with ProtectSystem=strict and NoNewPrivileges.\n\nFLASHDUTY\\_RUNNER\\_BIN\\_DIR is an explicit override and wins outright — the AGS cloud image bakes fduty at /usr/local/bin and points this env there.\n\nReturns \"\" only when neither an override nor a home dir can be resolved, in which case PATH is left untouched.\n\n```go\nfunc RunnerStateHome() string\n```\nRunnerStateHome resolves the runner's state/home root the same way cmd does (FLASHDUTY\\_RUNNER\\_HOME \u003e deprecated FLASHDUTY\\_RUNNER\\_WORKSPACE \u003e ~/.flashduty), so the bundled-tools dir always lands inside the writable state tree. Also the root under which self-update keeps the canonical runner binary (\\\u003chome\u003e/bin) when the running executable's own directory is read-only.\n\n```go\nfunc ShouldSkipForOutputsDir(command string) bool\n```\nShouldSkipForOutputsDir checks if large output processing should be skipped for commands operating on .outputs/ directory to avoid circular processing. Uses a word-boundary regex so commands like \"thread \" don't match \"head \".\n\n## Types\n\n```go\ntype Environment struct {\n\t// contains filtered or unexported fields\n}\n```\nEnvironment handles local filesystem operations.\n\n```go\nfunc New(root string, checker *permission.Checker) (*Environment, error)\n```\nNew creates a new workspace with the given root directory and permission checker.\n\n```go\nfunc (e *Environment) Bash(ctx context.Context, args *protocol.BashArgs) (*protocol.BashResult, error)\n```\nBash executes a bash command in the workspace.\n\n```go\nfunc (e *Environment) DeleteKnowledgeFiles(ctx context.Context, args *protocol.DeleteKnowledgeFilesArgs) (*protocol.DeleteKnowledgeFilesResult, error)\n```\nDeleteKnowledgeFiles removes the supplied files from the workspace root and scrubs their entries from the sentinel.\n\n```go\nfunc (e *Environment) Glob(ctx context.Context, args *protocol.GlobArgs) (*protocol.GlobResult, error)\n```\nGlob searches for files matching a pattern.\n\n```go\nfunc (e *Environment) Grep(ctx context.Context, args *protocol.GrepArgs) (*protocol.GrepResult, error)\n```\nGrep searches for a pattern in files.\n\n```go\nfunc (e *Environment) List(ctx context.Context, args *protocol.ListArgs) (*protocol.ListResult, error)\n```\nList lists entries in a directory.\n\n```go\nfunc (e *Environment) MCPCall(ctx context.Context, args *protocol.MCPCallArgs, logger *slog.Logger) (*protocol.MCPCallResult, error)\n```\nMCPCall executes an MCP tool call.\n\n```go\nfunc (e *Environment) MCPListTools(ctx context.Context, args *protocol.MCPListToolsArgs, logger *slog.Logger) (*protocol.MCPListToolsResult, error)\n```\nMCPListTools lists available tools from an MCP server.\n\n```go\nfunc (e *Environment) PackFolder(ctx context.Context, args *protocol.PackFolderArgs) (*protocol.PackFolderResult, error)\n```\nPackFolder walks args.Path, applies the skill exclusion rules, and returns a base64-encoded zip whose entries are rooted at the basename of args.Path.\n\n```go\nfunc (e *Environment) Read(ctx context.Context, args *protocol.ReadArgs) (*protocol.ReadResult, error)\n```\nRead reads a file from the workspace.\n\n```go\nfunc (e *Environment) ReconcileKnowledgeManifest(ctx context.Context, args *protocol.ReconcileKnowledgeManifestArgs) (*protocol.ReconcileKnowledgeManifestResult, error)\n```\nReconcileKnowledgeManifest reconciles the on-disk knowledge tree against the supplied manifest. Files present on disk but absent from the manifest are orphans (pruned). Files present in the manifest with a checksum that disagrees with the sentinel are stale (also pruned, so the next read triggers a fresh lazy install from Safari). Files whose checksum already matches are left in place.\n\nThe orphan prune is scope-bounded when the caller sends scope lists (see ReconcileKnowledgeManifestArgs): inside a staged scope the manifest is authoritative and orphans go; a scope that is valid account-wide but not staged by this session is another session's territory and is left alone; a scope outside ValidScopes no longer exists upstream and is pruned whole. Without scope lists (an older Safari) every orphan is pruned, as before.\n\nThe runner does NOT pre-stage anything in this call: the manifest declares what \\*should\\* exist if it were read, not what \\*must\\* be cached. Cold packs stay cold; only drift is corrected. The whole pass runs under the sentinel lock so it is safe with concurrent stage calls from the same Safari.\n\n```go\nfunc (e *Environment) Root() string\n```\nRoot returns the workspace root directory.\n\n```go\nfunc (e *Environment) StageKnowledgeFiles(ctx context.Context, args *protocol.StageKnowledgeFilesArgs) (*protocol.StageKnowledgeFilesResult, error)\n```\nStageKnowledgeFiles writes the supplied files into the workspace root and updates the sentinel checksum map.\n\n```go\nfunc (e *Environment) SyncSkill(ctx context.Context, args *protocol.SyncSkillArgs) (*protocol.SyncSkillResult, error)\n```\nSyncSkill is probe-or-install. With empty ZipData it checks local cache against args.Checksum: hit returns {Cached:true,Path}; miss returns {Cached:false,Path:\"\"} so the cloud retries with zip. With ZipData present it overwrites \\\u003chome\u003e/skills/\\\u003cname\u003e/ and writes .checksum.\n\nargs.SkillDir is accepted for backward compatibility but ignored — the runner derives the path from skill\\_name to keep layout under its control.\n\n```go\nfunc (e *Environment) WebFetch(ctx context.Context, args *protocol.WebFetchArgs) (*protocol.WebFetchResult, error)\n```\nWebFetch fetches content from a URL and converts it to readable format.\n\n```go\nfunc (e *Environment) Write(ctx context.Context, args *protocol.WriteArgs) error\n```\nWrite writes content to a file in the workspace.\n\n```go\ntype LargeOutputConfig struct {\n\tMaxOutputSize int\n\tPreviewSize   int\n\tPreviewLines  int\n}\n```\nLargeOutputConfig holds configuration for large output handling.\n\n```go\nfunc DefaultLargeOutputConfig() LargeOutputConfig\n```\nDefaultLargeOutputConfig returns the default configuration.\n\n```go\ntype LargeOutputProcessor struct {\n\t// contains filtered or unexported fields\n}\n```\nLargeOutputProcessor handles large output truncation and file storage.\n\n```go\nfunc NewLargeOutputProcessor(ws *Environment, config LargeOutputConfig) *LargeOutputProcessor\n```\nNewLargeOutputProcessor creates a new processor with the given workspace.\n\n```go\nfunc (p *LargeOutputProcessor) Process(ctx context.Context, content string, prefix string) (*ProcessResult, error)\n```\nProcess checks if content exceeds the limit and handles accordingly.\n\n```go\ntype LimitedWriter struct {\n\tW     io.Writer\n\tLimit int64\n\t// contains filtered or unexported fields\n}\n```\nLimitedWriter is an io.Writer that caps the total number of bytes forwarded to the wrapped writer. After the cap is reached it appends an inline marker once and then returns ErrOutputCapped on every subsequent write so callers can detect truncation via Hit().\n\nNOTE: exec.Cmd treats any writer error as fatal — callers wrapping LimitedWriter around a stdio pipe must filter ErrOutputCapped out of cmd.Run()'s error chain.\n\n```go\nfunc (l *LimitedWriter) Hit() bool\n```\nHit reports whether the writer's byte cap has been reached.\n\n```go\nfunc (l *LimitedWriter) Write(p []byte) (n int, err error)\n```\n\n```go\ntype ProcessResult struct {\n\tContent   string\n\tTruncated bool\n\tFilePath  string\n\tTotalSize int64\n}\n```\nProcessResult holds the result of processing large output.\n\n","path":"github.com/flashcatcloud/flashduty-runner/environment","name":"environment","synopsis":"Package workspace implements local workspace operations.","isRedistributable":true}
